7 .net delegates design-patterns
我想在VB.NET或C#或其他一些.NET语言中实现Observer模式.我听说代理可以用于此,但无法弄清楚为什么它们比观察者实现的普通旧接口更受欢迎.所以,
Ben*_*n M 27
当你可以直接调用一个方法,你并不需要一个代表.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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.
Chr*_*isW 22
你是O/S,我是一个应用程序.当你发现发生的事情时,我想告诉你调用我的一种方法.为此,我向你传递一个代表我想要你打电话给我的方法.我自己也不称之为我的那种方法,因为我希望你在发现某事时给它打电话.你不直接调用我的方法,因为你不知道(在编译时)该方法存在(我甚至没有在你建立时编写); 相反,您可以调用在运行时收到的委托指定的任何方法.
从技术上讲,您不必使用委托(除非使用事件处理程序,否则它是必需的).你可以没有他们.实际上,它们只是工具箱中的另一个工具.
关于使用它们的第一件事就是Inversion Of Control.只要你想控制函数在其外部的行为方式,最简单的方法就是将一个委托作为参数放置,让它执行委托.
实际上,委托传递的是对方法的引用,而不是对象...接口是对对象实现的方法子集的引用...
如果在应用程序的某个组件中,您需要访问对象的多个方法,则定义一个表示该对象方法子集的接口,并在您可能需要传递给该对象的所有类上分配和实现该接口组件...然后通过该接口而不是通过它们的具体类传递这些类的实例。
如果,在某些方法或组件中,您所需要的只是几个方法之一,这些方法可以位于任意数量的不同类中,但都具有相同的签名,那么您需要使用委托。
| 归档时间: |
|
| 查看次数: |
11946 次 |
| 最近记录: |