C# 代表的目的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/687626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:31:58  来源:igfitidea点击:

The purpose of delegates

c#.netdelegates

提问by KdgDev

Duplicate:

复制:

Difference between events and delegates and its respective applications

What are the advantages of delegates?

Where do I use delegates?

事件和委托的区别及其各自的应用

代表的优势是什么?

我在哪里使用委托?

I wonder what the purpose of delegates is. I haven't used them that much and can't really think of something.

我想知道代表的目的是什么。我没怎么用过它们,实在想不出什么。

In my courses, it's written that a delegate is a blue-print for all methods that comply with its signature.

在我的课程中,它写道,委托是所有符合其签名的方法的蓝图。

Also, you can add multiple methods to one delegate, and then they'll be executed after eachother in the order they were added. Which is probably only usefull for methods that affect local variables or methodes that don't return any values.

此外,您可以向一个委托添加多个方法,然后它们将按照添加的顺序依次执行。这可能仅对影响局部变量的方法或不返回任何值的方法有用。

I've read that C# implements Events as delegates, which is documented as being:

我读过 C# 将事件实现为委托,记录为:

//Summary: Represents the method that
will handle an event that has no event
data.

//Parameters:

//sender: The source of the event.

//e: An System.EventArgs that contains no event data.

[Serializable]

[ComVisible(true)] 

public delegate void EventHandler(object sender, EventArgs e);

Still, it's kinda confusing. Can someone give a good, usefull example of this concept?

尽管如此,它还是有点令人困惑。有人能给这个概念一个很好的、有用的例子吗?

采纳答案by Ian

Yeah,

是的,

You're almost there. A delegate refers to a method or function to be called. .NET uses the Events to say.. when someones presses this button, I want you to execute this piece of code.

您快到了。委托指的是要调用的方法或函数。.NET 使用事件说.. 当有人按下此按钮时,我希望您执行这段代码。

For example, in the use of a GPS application:

例如,在使用 GPS 应用程序时:

public delegate void PositionReceivedEventHandler(double latitude, double longitude);

This says that the method must take two doubles as the inputs, and return void. When we come to defining an event:

这表示该方法必须将两个双精度值作为输入,并返回 void。当我们定义一个事件时:

public event PositionReceivedEventHandler PositionReceived;  

This means that the PositionRecieved event, calls a method with the same definition as the PositionReceivedEventHandler delegate we defined. So when you do

这意味着 PositionRecieved 事件调用与我们定义的 PositionReceivedEventHandler 委托具有相同定义的方法。所以当你做

PositionRecieved += new PositionReceivedEventHandler(method_Name);

The method_Name must match the delegate, so that we know how to execute the method, what parameters it's expecting. If you use a Visual Studio designer to add some events to a button for example, it will all work on a delegate expecting an object and an EventArgs parameter.

method_Name 必须与委托匹配,以便我们知道如何执行该方法,它需要什么参数。例如,如果您使用 Visual Studio 设计器向按钮添加一些事件,则所有事件都将作用于需要对象和 EventArgs 参数的委托。

Hope that helps some...

希望能帮到一些...

回答by Jon

I can provide you with an example using a web application architecture:

我可以为您提供一个使用 Web 应用程序架构的示例:

Generally, with a web application you can provide a front controller that receives requests from many clients. We could put all our methods within the front controller for dealing with the many different types of requests from the clients. However, this get a little cumbersome. Instead we can use delegates to encapsulate functionality for different requests. We could have:

通常,对于 Web 应用程序,您可以提供一个前端控制器来接收来自许多客户端的请求。我们可以将所有方法放在前端控制器中,以处理来自客户端的许多不同类型的请求。然而,这变得有点麻烦。相反,我们可以使用委托来封装不同请求的功能。我们可以有:

  • Authentication Delegate
  • User Management Delegate
  • 认证委托
  • 用户管理委托

and so on. So it's a neat way to split up functionality into logical chunks - delegates. The Struts framework is based on this way of working (the ActionServlet and Action classes).

等等。因此,这是将功能拆分为逻辑块 - 委托的一种巧妙方式。Struts 框架基于这种工作方式(ActionServlet 和 Action 类)。

回答by Andrew Hare

There are lots of excellent articles explaining delegates - here are some good ones:

有很多很好的文章解释了代表——这里有一些很好的:

Delegates and events
C# Delegates Explained
Delegates in C#

委托和事件
C#的代表解释
代表在C#

回答by bendewey

As you noted a delegate is a way to create a signature for an method call. There are many great examples of using delegates, but the one that really opened my mind is this example.

正如您所指出的,委托是一种为方法调用创建签名的方法。使用委托有很多很好的例子,但真正让我大开眼界的是这个例子。

public delegate Duck GetDuckDelegate();

public GetDuckDelegate GiveMeTheDuckFactoryMethod(string type)
{
  switch(type)
  {
    case "Rubber":
      return new GetDuckDelegate(CreateRubberDuck);
    case "Mallard":
      return new GetDuckDelegate(CreateMallardDuck);
    default:
      return new GetDuckDelegate(CreateDefaultDuck);
  }
}

public Duck CreateRubberDuck()
{
  return new RubberDuck();
}

public Duck CreateMallardDuck()
{
  return new MallardDuck();
}

public Duck CreateDefaultDuck()
{
  return new Duck();
}

Then to use it

然后使用它

public static void Main() {
  var getDuck = GiveMeTheDuckFactoryMethod("Rubber");
  var duck = getDuck();
}

Arguably, the Factory pattern would be a better method for this, but I just thought up this example on the fly and thought it proved the point of how delegates can be treated as objects

可以说,工厂模式将是一个更好的方法,但我只是想了一下这个例子,并认为它证明了如何将委托视为对象

回答by SLaks

Delegates allow you to pass methods around like values.

委托允许您传递类似值的方法。

For example, .Net has a method called Array.ForEachthat takes a delegate and an array, and calls the delegate on each element of the array.

例如,.Net 有一个被调用的方法Array.ForEach,它接受一个委托和一个数组,并在数组的每个元素上调用委托。

Therefore, you could write,

因此,你可以写,

int[] arr = new int[] { 1, 2, 4, 8, 16, 32, 64 };
Array.ForEach(arr, new Action<int>(Console.WriteLine));

This code will call Console.WriteLinefor each number in the array.

此代码将调用Console.WriteLine数组中的每个数字。

There are many things you can do by making functions that take delegates, especially when combined with anonymous methods. For examples, look at LINQ.

通过创建接受委托的函数,您可以做很多事情,尤其是与匿名方法结合使用时。例如,看看LINQ

回答by KaptajnKold

Delegates, to my understanding, provides a way of specializing the behavior of a class without subclassing it.

就我的理解,委托提供了一种专门化类的行为而无需对其进行子类化的方法。

Some classes have complex generic behavior, but are still meant to be specialized. Think of a Window class in a GUI framework: A Window can propably do a lot on it's own, but you would most likely still want to specialize it in some way. In some frameworks, this is done via inheritance. A different way of doing it is with delegates. Say you want something to happen when the Window resizes: Your delegate class can then implement a method called onWindowResize (provided of course that the Window class supports this), which gets called whenever the Window resizes and is responsible for any specialized behavior when the Window resizes.

一些类具有复杂的通用行为,但仍然是专门的。想想 GUI 框架中的 Window 类:一个 Window 可以自己做很多事情,但您很可能仍然希望以某种方式专门化它。在某些框架中,这是通过继承完成的。一种不同的方式是使用委托。假设您希望在 Window 调整大小时发生某些事情:然后您的委托类可以实现一个名为 onWindowResize 的方法(当然前提是 Window 类支持此方法),该方法在 Window 调整大小时被调用,并负责在 Window调整大小。

I'm not going to argue the merits of delegation over inheritance, but suffice it to say that there are many who feel that delegation is "cleaner" than inheritance.

我不打算争论委托优于继承的优点,但我只想说有很多人认为委托比继承“更干净”。

回答by KaptajnKold

Many people initially get confused with the real need for delegates and events. I was one of them and it took me some time to figure it out :-). Recently answered a similar query in ASP.NET forums and thought it would be good if I create a blog post on this topic! Here was the query:

许多人最初对委托和事件的真正需求感到困惑。我是其中之一,我花了一些时间才弄明白:-)。最近在 ASP.NET 论坛中回答了一个类似的问题,并认为如果我创建一篇关于这个主题的博客文章会很好!这是查询:

"I was reading an example somewhere of a Bank Class that if the minimum balance is reached you need to inform the rest of the app that the min has reached, but can't we do that by just calling a normal method. for example: lets say when we deduct some amount from the balance and if minimum reached then call some method to take some action, I am totally missing why do we need delegates and custom events here?"

“我正在阅读银行类某处的示例,如果达到最低余额,您需要通知应用程序的其余部分已达到最低余额,但我们不能仅通过调用正常方法来做到这一点。例如:假设当我们从余额中扣除一些金额并且如果达到最小值然后调用某种方法来采取一些行动时,我完全不明白为什么我们需要委托和自定义事件?”

Thing is in the Bank case, you can definitely call a method, but then it would be simple procedural programming, we need event based programming when we want our code to respond to some events generated by a system.

事情是在 Bank 的情况下,您绝对可以调用一个方法,但是这将是简单的过程编程,当我们希望我们的代码响应系统生成的某些事件时,我们需要基于事件的编程。

For eg.: think that windows OS is a system, and we are writing a code (in any language) where we want to capture an event like mouse_click(). Now how would our program know that a mouse click has occured? We can use low level code for it, but since OS is already handling low level code, its best to capture an event raised by the OS.

例如:认为 Windows 操作系统是一个系统,我们正在编写一个代码(用任何语言),我们想在其中捕获像 mouse_click() 这样的事件。现在我们的程序如何知道发生了鼠标点击?我们可以使用低级代码,但由于操作系统已经在处理低级代码,因此最好捕获操作系统引发的事件。

In other terms, the moment a mouse_click() happens the OS fires an event. The OS doesnt care who captures this event and uses it, it just sends out a notification. Then any code (like ours) can capture that event and use it accordingly. This saves us a lot of time to write code for the same ourselves. And other programs too can use the same event and handle it accordingly.

换句话说,当 mouse_click() 发生时,操作系统会触发一个事件。操作系统不关心谁捕获了这个事件并使用它,它只是发出一个通知。然后任何代码(如我们的)都可以捕获该事件并相应地使用它。这为我们节省了很多时间来为自己编写代码。其他程序也可以使用相同的事件并相应地处理它。

Similarly, the banking system can be huge, and many other outside applications might be accessing it. The banking system does not know how many such applications there are which need it, or are dependent on it, and how would they handle certain situations like when balance is low, so it simply fires an event whenever low balance occurs, and this event can be used by any other code, besides banking code itself.

同样,银行系统可能非常庞大,许多其他外部应用程序可能正在访问它。银行系统不知道有多少这样的应用程序需要或依赖它,也不知道它们将如何处理某些情况,例如余额不足时,因此只要发生余额不足时,它就会触发一个事件,并且此事件可以除了银行代码本身之外,任何其他代码都可以使用。

Note that each susbcriber to that event can handle that event independently, for eg. the banking code might stop something from executing if balance is low, some other reporting app might send an email in such a case, or some ATM code can stop a particualr transaction and notify the user that balance is low.

请注意,该事件的每个订阅者都可以独立处理该事件,例如。如果余额不足,银行代码可能会停止执行某些操作,其他一些报告应用程序可能会在这种情况下发送电子邮件,或者某些 ATM 代码可以停止特定交易并通知用户余额不足。

Hope this clears things a bit!

希望这能让事情变得更清楚!