简体   繁体   English

为什么在.Net中使用代理

[英]Why to use delegates in .Net

I was reading some article which was describing the use of delegates by the following example which shows the use of multicast delegate 我正在阅读一些文章,该文章通过以下示例描述了委托的使用,该示例显示了多播委托的使用

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

But from my understanding of the code I think same can be done using a class and having the same functions which define the tasks done by delegate handlers as follows 但是根据我对代码的理解,我认为可以使用类来完成同样的功能,并且具有相同的功能,这些功能定义委托处理程序完成的任务,如下所示

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

and changing the Utility class HardWork() as follows 并按如下方式更改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);
        }
    }
}

So my question with respect to this code is, why do we actually need a delegate in first place? 所以我对这段代码的问题是,为什么我们实际上需要一个代表呢?

Some of the reasons(plz correct if I am wrong) which I think we need the delegate are as follows- 我认为我们需要代表的一些原因(如果我错了,则正确)(如下所示)如下 -

  1. If we need notification in the Program class itself, then we need delegates. 如果我们需要在Program类本身中进行通知,那么我们需要委托。
  2. With the help of multicast delegate we can call multiple functions at the same time in place of calling them multiple times(as in my second case). 在多播委托的帮助下,我们可以同时调用多个函数代替多次调用它们(如我的第二种情况)。

A delegate is a way to have a reference to a particular method as a variable, meaning it can change, instead of as your last example, hardcoding into the program which methods to call. 委托是一种将特定方法作为变量引用的方法,这意味着它可以更改,而不是作为最后一个示例,硬编码到程序中调用哪些方法。

Are there way to do this without delegates? 没有代表,有没有办法做到这一点? Sure, you can provide objects that override methods or use classes that implements interfaces, but delegates are cheaper in the sense that you don't need a whole type wrapped around the single method. 当然,您可以提供覆盖方法或使用实现接口的类的对象,但是代理在您不需要围绕单个方法的整个类型的意义上更便宜。

Examples of situations where hardcoding won't do, and interfaces/overriding methods would be more work than delegates, try looking at visual components and their events. 硬编码不起作用的情况的例子,接口/覆盖方法比代表更多的工作,尝试查看可视组件及其事件。 Events in .NET use delegates. .NET中的事件使用委托。 You can simply double-click on a button in the visual designer in Visual Studio and it will create the method for you and wire it up to the event by the way of a delegate. 您只需双击Visual Studio中可视化设计器中的按钮,它就会为您创建方法,并通过委托方式将其连接到事件。 Having to create a class, or implement an interface on top of the form class would be a lot more work, and especially if you have multiple buttons that you would want to do different things, then you definitely need multiple objects implementing those interfaces. 必须创建一个类,或者在表单类之上实现一个接口会有很多工作,特别是如果你有多个按钮要做不同的事情,那么你肯定需要多个对象来实现这些接口。

So delegates have their place, but your examples doesn't do them justice. 代表们有他们的位置,但你的例子不公平。

Here is a LINQPad example that demonstrates that one method ( DoSomething ) can end up doing different things depending on the delegate provided to it: 这是一个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");
}

This will first log to the console, then rerun the method and log to a file. 这将首先登录到控制台,然后重新运行该方法并登录到文件。

Use a delegate in the following circumstances 1.An eventing design pattern is used (Event handlers ) 2.A class may need more than one implementation of the method 3.Thread implementation (Thread Start, sleep etc ) 在以下情况下使用委托1.使用事件设计模式(事件处理程序)2.A类可能需要方法的多个实现3.Thread实现(线程启动,睡眠等)

for more info refer https://msdn.microsoft.com/en-us/library/ms173173.aspx : 有关更多信息,请参阅https://msdn.microsoft.com/en-us/library/ms173173.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM