简体   繁体   中英

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 ). 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.

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:

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. 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.

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 .

TickerUpdated needs to have a signature that matches your UpdateEventHandler definition:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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