使用代表的好处?

0

本文介绍了使用代表的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我希望在 VB.NET 或 C# 或其他一流的 .NET 语言中实现观察者模式.我听说委托可以用于此目的,但无法弄清楚为什么它们比在观察者上实现的普通旧接口更受欢迎.所以,

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 out why they would be preferred over plain old interfaces implemented on observers. So,

  • 为什么我应该使用委托而不是定义自己的接口并传递对实现它们的对象的引用?
  • 为什么我要避免使用委托,而使用良好的老式接口?

推荐答案

当您可以直接调用方法时,您不需要委托.

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

如您所见,Task 类不知道也不关心——在这种情况下——委托是一个将任务状态打印到控制台的方法.该方法同样可以通过网络连接将状态发送到另一台计算机.等等.

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.

这篇关于使用代表的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14

函数委托与函数
Func Delegate vs Function(函数委托与函数)...
2023-11-11 C#/.NET开发问题
6