Advantages of using delegates?

前端 未结 14 1355
渐次进展
渐次进展 2020-12-13 11:39

I\'m looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I\'ve heard that delegates can be used for this, but can\'t figure ou

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 12:20

    When you can directly call a method, you don't need a delegate.

    A delegate is useful when the code calling the method doesn't know/care what the method it's calling is -- for example, you might invoke a long-running task and pass it a delegate to a callback method that the task can use to send notifications about its status.

    Here is a (very silly) code sample:

    enum TaskStatus
    {
       Started,
       StillProcessing,
       Finished
    }
    
    delegate void CallbackDelegate(Task t, TaskStatus status);
    
    class Task
    {
        public void Start(CallbackDelegate callback)
        {
            callback(this, TaskStatus.Started);
    
            // calculate PI to 1 billion digits
            for (...)
            {
                callback(this, TaskStatus.StillProcessing);
            }
    
            callback(this, TaskStatus.Finished);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Task t = new Task();
            t.Start(new CallbackDelegate(MyCallbackMethod));
        }
    
        static void MyCallbackMethod(Task t, TaskStatus status)
        {
            Console.WriteLine("The task status is {0}", status);
        }
    }
    

    As you can see, the Task class doesn't know or care that -- in this case -- the delegate is to a method that prints the status of the task to the console. The method could equally well send the status over a network connection to another computer. Etc.

提交回复
热议问题