简体   繁体   English

在C#中实现事件

[英]Implementation of an Event in C#

Right, I have read all the pages I can get my hands on that provide simple implementation of event in C# ( 1 , 2 , 3 ). 对了,我看了所有我能得到我的手是提供C#(简单的实现事件的页123 )。 I just can't get my event to work. 我只是无法让我的活动正常进行。 I am porting a program from VB.net where it was super easy to use events. 我正在从VB.net移植程序,该程序非常易于使用。

So the class that raises the event: 因此引发事件的类:

class TickerClass
    {

        // Event Setup
    public EventArgs e = null;
    public delegate void UpdateEventHandler(TickerClass t, EventArgs e);
    public event UpdateEventHandler Update;

    void doSomethingAndRaiseTheEvent()
    {
        Update(this, null);
    }
}

The class that instantiates the TickerClass and handles the event: 实例化TickerClass并处理事件的类:

public class Engine
{

   TickerClass ticker;

   // constructor
   public Engine()
   {
       ticker = new TickerClass();

       // subscribe to the event
       ticker.Update += new TickerClass.UpdateEventHandler(TickerUpdated);
   }

   // method to call when handling the event
   public void TickerUpdated()
   {
    //do stuff with ticker
   }

}

What is wrong with this implementation? 此实现有什么问题?

Your event handler doesn't match the signature of the delegate used to define the event, as I'm sure the error message you're getting tells you. 您的事件处理程序与用于定义事件的委托的签名不匹配,因为我确定您收到的错误消息会告诉您。

The even't signature indicates that it accepts a TickerClass and an EventArgs as parameters to the method. 偶数签名表示它接受TickerClassEventArgs作为方法的参数。 Your event handler has neither. 您的事件处理程序都没有。

Once you fix the signature the example will be working. 修复签名后,该示例将起作用。

Note that there isn't any particular reason to define your own custom delegate; 请注意,定义您自己的自定义委托没有任何特殊原因; you can just use Action instead, just for convenience's sake. 为了方便起见,您可以改用Action

You also don't need to explicitly state the type of the delegate when adding the event handler. 添加事件处理程序时,您也不需要明确声明委托的类型。 The compiler can infer it when given ticker.Update += TickerUpdated . 给定ticker.Update += TickerUpdated时,编译器可以进行推断。

TickerUpdated needs to have a signature that matches your UpdateEventHandler definition: TickerUpdated需要具有一个与您的UpdateEventHandler定义相匹配的签名:

public void TickerUpdated(TickerClass sender, EventArgs e)
{
    // This will work now

Note that, instead of passing null when raising the event, it would also be a good idea to use EventArgs.Empty , and also check for null on the handler in the idiomatic way: 请注意,除了在引发事件时传递null ,使用EventArgs.Empty并以惯用的方式在处理程序上检查null也是一个好主意:

void doSomethingAndRaiseTheEvent()
{
    var handler = this.Update;
    if (handler != null)
        handler(this, EventArgs.Empty);
}

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

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