2012-07-06 48 views
3

我有一個執行長任務的函數,我想偶爾用其他狀態更新來更新變量。 (如果有更好的方法來做這件事,那也沒關係)我正在編寫一個庫,這個代碼可能會一次調用多次,因此在存儲變量的同一個類中創建另一個變量不是一個選項。這裏是我的代碼是什麼樣子:發送一個對變量的引用而不是它的值

public static bool Count(int Progress, int CountToWhat) { 
    for (int i = 0; i < CountToWhat; i++) { 
     Progress = CountToWhat/i; // This is how I'd like to update the value, but obviously this is wrong 
     Console.WriteLine(i.ToString()); 
    } 
} 
+1

你有沒有考慮過不做這個靜態?然後你可以在課堂上保留一個變量。 – JamieSee 2012-07-06 15:08:23

回答

3

更改簽名:

public static bool Count(ref int Progress, int CountToWhat) 

當你罵它在變量之前使用ref關鍵字e你作爲第一個參數傳入。

+0

謝謝,這是最簡單的解決方案。 – Oztaco 2012-07-06 18:03:18

2

您可以使用

int Progress = 0; 
public static bool Count(ref int Progress, int CountToWhat) 
{ 
    .... 
} 

或者

int Progress; //without init 
public static bool Count(out int Progress, int CountToWhat) 
{ 
    .... 
} 
+0

你是什麼意思,*「引用是用於不在原始類型上的類。」*?另外你*可能*使用out/ref,但它不是唯一的方法。 – Servy 2012-07-06 15:12:05

+0

如果使用Class1作爲參數測試此方法,則爲public void Test(Class1 value){...};你不需要添加關鍵詞作爲ref或out ,,, – 2012-07-06 15:17:56

+0

在某些情況下,仍然有一個目的是在課堂上使用ref/out。無論如何,我的觀點是,它的措辭很差,不能理解,因爲它是目前寫的。 – Servy 2012-07-06 15:20:54

4

這不是爲呼叫者提供更新的好方法。

更好的是,您可以在類庫中定義一個或多個事件(如OnError,OnProgress等)。 您可以提高,例如,OnProgress當你想在某一操作通知進度:

for (int i = 0; i < CountToWhat; i++) { 
    OnProgress(CountToWhat/i); 
    Console.WriteLine(i.ToString()); 
} 

這是做它的一種更好的方式,從工作線程通知時尤其如此。

+3

如果靜態事件處理程序對您的具體情況沒有多大意義,則可以改爲使該方法回調,例如, '公共靜態布爾計數(INT進步,int CountToWhat,行動 OnProgress)''。這樣它的本地範圍而不是靜態的。 – 2012-07-06 15:13:32

+0

@TimS .:當然,回調總是一個很好的選擇,即使在非靜態情況下。 – 2012-07-06 15:16:51

+1

雖然我爲''ref''回答了因爲它們會起作用而回答的問題,但這是實現此結果的**首選**方法。 – Nate 2012-07-06 15:26:35

1

一個更好的方法可能是通過一個Action<int>委託被調用,以報告進展情況:

public static bool Count(int CountToWhat, Action<int> reportProgress) 
{ 
    for (int i = 0; i < CountToWhat; i++) 
    { 
     var progress = CountToWhat/i; 
     reportProgress(progress); 
     Console.WriteLine(i.ToString()); 
    } 
} 

,那麼你會用它想:

Count(100, p => currentProgress = p); 

您也可以使用BackgroundWorker類運行長時間運行的任務,並利用其ProgressChanged事件。

相關問題