簡體   English   中英

為什么在.Net中使用代理

[英]Why to use delegates in .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());
    }
}

並按如下方式更改Utility類HardWork()

 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);
        }
    }
}

所以我對這段代碼的問題是,為什么我們實際上需要一個代表呢?

我認為我們需要代表的一些原因(如果我錯了,則正確)(如下所示)如下 -

  1. 如果我們需要在Program類本身中進行通知,那么我們需要委托。
  2. 在多播委托的幫助下,我們可以同時調用多個函數代替多次調用它們(如我的第二種情況)。

委托是一種將特定方法作為變量引用的方法,這意味着它可以更改,而不是作為最后一個示例,硬編碼到程序中調用哪些方法。

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

硬編碼不起作用的情況的例子,接口/覆蓋方法比代表更多的工作,嘗試查看可視組件及其事件。 .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");
}

這將首先登錄到控制台,然后重新運行該方法並登錄到文件。

在以下情況下使用委托1.使用事件設計模式(事件處理程序)2.A類可能需要方法的多個實現3.Thread實現(線程啟動,睡眠等)

有關更多信息,請參閱https://msdn.microsoft.com/en-us/library/ms173173.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM