close
文章出處

      Delegate是.NET的一個重要特性,并且非常有用。
      也許知道delegate是怎么回事情但是如果沒有用過它,就不會更深刻的認識它。好比看的懂某個知識點的代碼,但是并不一定真的懂這個知識點。
      對于此,我身有體會,我對delegate的了解就是這樣一種情況。
      還記得以前用C/C++寫代碼,CallBack感覺用起來不順手。在.net里,delegate可以實現類似的功能。
      舉個大家可能碰到過的例子--進度(條)的問題。
      在程序處理一個比較長的過程時,如果能顯示進度,對于客戶來說是非常棒的事情,但是一個比較大的程序很有可能會分層,而通常會把邏輯放到BLL層。
     這個時候就有一個問題,如何把程序的進度顯示給客戶呢?答案就是用delegate。
    具體說說吧。
    假設你想合并兩個文件。
    步驟是:
     Step1: 讀取文件1
     Step 2: 讀取文件2
     Step 3:合并文件1 和文件2
    
    如何把這些信息提示給用戶呢?
   具體實現如下(偽代碼)
  
   A) BLL層

 1public class Combinator
 2{
 3  public string FilePath1;
 4  public string FilePath2;
 5  public SetProgressText OnProgressText;
 6  
 7  public void Process()
 8  {
 9    this.OnProgressText(" Loading" +FilePath1+"")
10    Load(FilePath1);
11        this.OnProgressText(" Loading" +FilePath2+"")
12    Load(FilePath2);
13       this.OnProgressText("Combining these 2 files");
14    Combine();
15   this.OnProgressText("Finished combining these 2 files!");
16  }

17
18  private void Load(string path)
19  {
20     //The logic to load file
21   }

22   private void Combine()
23{
24  //The logic to combine 2 files
25}

26  ///
27  ///Delegate.
28  ///To set the progress text to user.
29  ///

30  public delegate void SetProgressText(string text);
31}
 

  看看Line 5, 30,這里是delegate的定義。

  B) UI層
 
 1public class Form1
 2{
 3  private Label lblStatus=new Label();
 4  private Button btnCombine=new Button();
 5  private void btnCombine_click(Object o,EventArgs e)
 6 {
 7  Combinator combine=new Combinator();
 8  combine.OnSetProgressText=new SetProressText(SetStatus);
 9  combine.Process();
10  }

11  private void SetStatus(string text)
12  {
13   this.lblStatus.Text=text;
14  }

15}
 
    看看以上代碼的Line8,這里需要給Combinator的OnSetProgressText Delegate一下,指向SetStatus就可以了。注意,SetStatus的參數定義必須和SetProgress的定義相同,不然就不叫delegate,當然編譯也通不過。
 
   這是delegate的一個簡單應用,但是很有幫助喲。 

  更新:
   Delegate可以傳遞的,具體如下: 假設A類調用B類,調用了C,而C類又定義了Delegate。可以在B類里定義C類的Delegate屬性,然后在A類定義B類的delegate的目標函數,即實現方法。其實A類的實現函數就是C的delegate的目標函數。
                                                                                                                                                           Last Updated 2006年3月23日

不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    AutoPoster 發表在 痞客邦 留言(0) 人氣()