简体   繁体   中英

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

 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.
  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. 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. 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:

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 )

for more info refer https://msdn.microsoft.com/en-us/library/ms173173.aspx :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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