简体   繁体   English

如何与委托一起使用事件

[英]How to use an event with a delegate

As far as I know the only thing about delegates is that , delegate is: 据我所知,关于委托的唯一事情是,委托是:

  • A pointer to a method. 指向方法的指针。

  • And it can call multiple methods at once. 它可以一次调用多个方法。

But something I can't understand is that some users are declaring an event with the eventhandler the delegate. 但是我无法理解的是,有些用户正在使用事件处理程序委托来声明事件。 For example: 例如:

public void delegate MyDelegate(string Name);
public event MyDelegate EventOfDelegate;

But I don't know what's with the event with the eventhandler of the delegate . 但是我不知道委托的事件处理程序有什么事件。 Can someone explain to me what's with the event? 有人可以向我解释一下这次活动吗? where I can use it and if the eventhandler is the name of the delegate what it means? 我可以在哪里使用它,如果eventhandler是委托的名称,这意味着什么?

Take some time to read this article that describes delegates and their relation to events. 花一些时间阅读这篇介绍代理及其与事件关系的文章 I believe it's written by the renown Jon Skeet . 我相信它是由著名的Jon Skeet撰写的。

you assign some Delegate to EventOfDelegate(As you declared in code). 您将一些委托分配给EventOfDelegate(如您在代码中声明的那样)。 Example EventOfDelegate+= new MyDelegate(arg); 示例EventOfDelegate+= new MyDelegate(arg);

Where arg is action to do when event get's called. arg是调用事件get时要执行的操作。

Then when we want to use that event we do 然后,当我们想使用该事件时,

if (EventOfDelegate != null) // check if we assigned it
    EventOfDelegate(arg);
public delegate void MyDelegate(string Name);

This line is declaring a delegate with a void return type and a single input parameter of type string. 此行声明的委托具有空返回类型和一个字符串类型的单个输入参数。 It is then used in the following event declaration, which basically means that the subscribers of this event must have the same signature defined previously in the delegate definition (more or less, read here for more info about the topic). 然后在以下事件声明中使用它,这基本上意味着该事件的订阅者必须具有与委托定义中先前定义的相同的签名(或多或少,请在此处阅读有关该主题的更多信息)。

As you can see in the question posted by @Oded: 正如您在@Oded发表的问题中所看到的:

An Event declaration adds a layer of abstraction and protection on the delegate instance. 事件声明在委托实例上添加了一层抽象和保护。 This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list. 此保护可防止委托的客户端重置委托及其调用列表,并且仅允许在调用列表中添加或删除目标。

This is needed because, using delegates and events, two roles appear: the broadcaster and the subscriber . 这是必需的,因为使用委托和事件会出现两个角色: 广播者订户

From the " C# 4 in a Nutshell " book: 摘自“ C#4简而言之 ”一书:

The broadcaster is a type that contains a delegate field. 广播者是一种包含委托字段的类型。 The broadcaster decides when to broadcast, by invoking a delegate. 广播公司通过调用代表来决定何时广播。

The subscribers are the method target recipients. 订阅者是方法目标接收者。 A subscriber decides when to start and stop listening, by calling += and -= on the broadcaster's delegate. 订户通过调用广播代理的+ =和-=来决定何时开始和停止收听。 A subscriber does not know about, or interfere with, other subscribers. 一个订户不了解或干扰其他订户。

Then, an event is a construct used to expose the delegate features required for this model, the subscriber/broadcaster model. 然后,事件是用于暴露此模型(订户/广播模型)所需的委托功能的构造。 The main purpose of events is to prevent subscribers from interfering with each other. 事件的主要目的是防止订户相互干扰。 For example: 例如:

Consider a friend and yourself. 考虑一个朋友和你自己。 You sign an agreement with your friend. 您与朋友签署协议。 This agreement consists of: 该协议包括:

  • When you have finished doing an activity, your friend has to inform other friends about the end of your activity. 完成活动后,您的朋友必须通知其他朋友您的活动结束。 Those friends have to do other activities. 那些朋友必须做其他活动。

In this case, you are the broadcaster , your friend is a subscriber , the end of your activity is the event . 在这种情况下,您是广播公司 ,您的朋友是订户 ,您的活动结束是活动 What about the delegate? 代表呢? The delegate is your friend, because he has to give the news to other friends about the end of your activity, in order to let them doing other activities. 代表是您的朋友,因为他必须向其他朋友发送有关您活动结束的消息,以便他们进行其他活动。

In other terms: 换句话说:

public delegate void PriceChangedHandler(decimal oldPrice, decimal newPrice);

public class Stock
{
    string symbol;
    decimal price;

    public Stock(string symbol) { this.symbol = symbol; }

    public event PriceChangedHandler PriceChanged;

    public decimal Price
    {
        get {return Price;}
        set
        {
            if(price == value) return;
            if(PriceChanged != null) /* if invocation list is not empty, fire the event */
                PriceChanged(price, value);
            price = value;
        }
    }

You can see that the Stock class fires its PriceChanged event every time the Price of the Stock changes. 你可以看到, Stock类火灾的PriceChanged每一次事件的PriceStock变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM