How to create a common event creation method

I have a set of events that have the same signature. Now I am wondering if I can create a common event handler processing method to do this for all events?

  • Is it possible to send an event like <T>?
+5
source share
3 answers

If it's all within the same class, you can make a way to raise an event that works with any of them. For example, if your events were EventHandler<T>, you could use:

private void RaiseEvent<T>(EventHandler<T> eventHandler, T eventArgs)
{
    if (eventHandler != null)
    {
        eventHandler(this, eventArgs);
    } 
}

Then you can call this via:

this.RaiseEvent(this.MyEvent, new MyEventArgs("Foo"));
+10
source

For a static version of Reed Copsi's answer, I created a static class Event:

public static class Event
{
    public static bool Raise<T>(Object source, EventHandler<T> eventHandler, T eventArgs) where T : EventArgs
    {
        EventHandler<T> handler = eventHandler;
        if (handler != null)
        {
            handler(source, eventArgs);
            return true;
        }
        return false;
    }
}

, EventHandler<T>. void bool , - . , void.

:

public event EventHandler<FooArgs> FooHappend;

public void Foo()
{
    Event.Raise(this, FooHappend, new FooArgs("Hello World!");
}
+1

See this . He describes what you want.

You can create a typed event using a typed delegate and use it for your event:

public delegate void myDel<T>(T stuff);

public event myDel<int> myEvent;

public doStuff()
{
    myDel(1);
}
-1
source

All Articles