代表们的目的目的、代表

2023-09-02 01:22:33 作者:久而久之就不痛不痒了

Difference事件和代表及其相应的应用程​​序之间

什么是代表的优势是什么?

我在哪里可以使用委托?

我不知道代表的目的是什么。我没有使用过他们多少并不能真正想到的东西。

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.

此外,您还可以添加多个方法来一名代表,然后他们会后海誓山盟在它们的添加顺序执行。这可能是唯一有用的,影响局部变量或methodes不返回任何值的方法。

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.

我读过,C#实现活动为代表,其记录为:

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

//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?

推荐答案

是啊,

您快到了。委托是指方法或函数被调用。 .NET使用事件说..当某人presses这个按钮,我要你执行这片code。

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.

例如,在使用GPS应用程序的

For example, in the use of a GPS application:

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

这表示该方法必须采用两个双打作为输入,并返回void。当我们来定义一个事件:

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

public event PositionReceivedEventHandler PositionReceived;

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

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

PositionRecieved += new PositionReceivedEventHandler(method_Name);

在METHOD_NAME必须委托匹配,让我们知道如何执行的方法,什么参数它的预期。如果您使用Visual Studio设计一些活动增加,例如一个按钮,它会在一个委托的所有工作期待的对象和EventArgs的参数。

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.

希望帮助一些...

 
精彩推荐
图片推荐