使用委托的优势? [英] Advantages of using delegates?
问题描述
我在找实现在VB.NET观察者模式或者C#或其他一些一流的.NET语言。我听说,代表可用于这一点,但想不通他们为什么会pferred了关于观察员执行普通的老式接口$ P $。因此,
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,
- 为什么要使用委托而不是定义自己的接口,并通过周围对象的引用实现它们?
- 为什么我可能要避免使用代表,并有很好的ol'派接口去?
推荐答案
当你可以直接调用一个方法,你的不的需要委托。
When you can directly call a method, you don't need a delegate.
在code调用该方法不知道/关心什么方法,它调用的是的委托是有用的它委托给该任务可以用它来发送通知有关其状态的回调方法。
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.
下面是一个(很无聊)code样品:</ P>
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.
这篇关于使用委托的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!