2014-06-26 55 views
1

我讀了一些文章這是由下面的例子 描述用代表這表明使用多播委託爲什麼要使用委託在.net

public delegate void ProgressReporter(int percentComplete); 
class Program 
{ 
    static void Main(string[] args) 
    { 
     ProgressReporter p = WriteProgressToConsole; 
     p += WriteProgressToFile; 
     Utility.HardWork(); 
    } 

    private static void WriteProgressToConsole(int percentComplete) 
    { 
     Console.WriteLine(percentComplete); 
    } 

    private static void WriteProgressToFile(int percentComplete) 
    {   
     System.IO.File.WriteAllText("progress.txt", percentComplete.ToString());   
    } 
} 


    public static class Utility 
{ 
    public static void HardWork(ProgressReporter p) 
    { 
     for (int i = 0; i < 10; i++) 
     {  
      p(i); 
      System.Threading.Thread.Sleep(1000); 
     } 
    } 
} 

但是從我的,我認爲代碼的理解同樣可使用的一類,並具有限定由委託處理程序完成的任務如下

public static class ProgressReporter 
{ 
    public static void WriteProgressToConsole(int percentComplete) 
    { 
     Console.WriteLine(percentComplete); 
    } 

    public static void WriteProgressToFile(int percentComplete) 
    { 
     System.IO.File.WriteAllText("progress.txt", percentComplete.ToString()); 
    } 
} 

並改變工具類勤勞()如下

0123相同的功能來實現
public static class Utility 
{ 
    public static void HardWork() 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      ProgressReporter.WriteProgressToConsole(i * 10); 
      ProgressReporter.WriteProgressToFile(i * 10); 
      System.Threading.Thread.Sleep(1000); 
     } 
    } 
} 

所以我關於這個代碼的問題是,爲什麼我們實際上首先需要一個委託?

一些原因(PLZ糾正如果我錯了),我認爲我們需要委託如下 -

  1. 如果我們在程序類本身需要通知,那麼我們需要的代表。
  2. 在多播委託的幫助下,我們可以同時調用多個函數,而不是多次調用它們(如我的第二種情況)。
+0

可能重複(http://stackoverflow.com/questions/3567478/delegates-why) –

回答

3

委託是一種將特定方法引用爲變量的方法,這意味着它可以改變,而不是作爲最後一個例子,在程序中硬編碼調用哪些方法。

有沒有辦法做到這一點,沒有代表?當然,您可以提供覆蓋方法或使用實現接口的類的對象,但代理更便宜,因爲您不需要圍繞單一方法的整個類型。

硬編碼不會執行的情況和接口/覆蓋方法比代表更多的工作,嘗試查看可視組件及其事件。 .NET中的事件使用委託。您可以簡單地雙擊Visual Studio中的可視化設計器中的按鈕,它將爲您創建方法,並通過委託方式將其連接到事件。不得不創建一個類,或者在窗體類的頂部實現一個接口,這將需要更多的工作,特別是如果你有多個按鈕需要做不同的事情,那麼你肯定需要多個實現這些接口的對象。

所以,代表們有自己的位置,但你的例子並不公平。

這裏是一個LINQPad例子表明,一種方法(DoSomething)可以最終做取決於提供給它的代表不同的事情:

void Main() 
{ 
    DoSomething(msg => Console.WriteLine(msg)); 

    using (var writer = new StreamWriter(@"d:\temp\test.txt")) 
    { 
     DoSomething(msg => writer.WriteLine(msg)); 
    } 
} 

public delegate void LogDelegate(string message); 

public static void DoSomething(LogDelegate logger) 
{ 
    logger("Starting"); 
    for (int index = 0; index < 10; index++) 
     logger("Processing element #" + index); 
    logger("Finishing"); 
} 

這將首先登錄到控制檯,然後重新運行方法並登錄到一個文件。

相關問題