I have a set of events that have the same signature . now I wonder if I can create a generic event handler raising method to do this for all of the events ?
<T>
?Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .
The EventArgs class is the base class for all the event data classes. . NET includes many built-in event data classes such as SerialDataReceivedEventArgs. It follows a naming pattern of ending all event data classes with EventArgs. You can create your custom class for event data by deriving EventArgs class.
An event handler is the subscriber that contains the code to handle specific events. For example, an event handler can be used to handle an event that occurs during the click of a command button in the UI. In C#, an event is connected to its handler by an event delegate.
Invoke(this, e); handler(this, e) will call every registered event listener. Event listeners subscribe with help of the += operator and unsubscribe with -= operator to that event. this is there to give the event listener to know who raised the ThresholdReached event.
If this is all within a single class, you can make a method to raise the event which works with any of them. For example, if your events all were EventHandler<T>
, you could use:
private void RaiseEvent<T>(EventHandler<T> eventHandler, T eventArgs)
{
if (eventHandler != null)
{
eventHandler(this, eventArgs);
}
}
You could then call this via:
this.RaiseEvent(this.MyEvent, new MyEventArgs("Foo"));
For a static version of Reed Copsey's reply, 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;
}
}
This also assumes your event handlers are of the type EventHandler<T>
. The return type was changed from void
to bool
and returns whether there were any listeners of the event. Rarely used, so feel free to change back to void
.
Example usage:
public event EventHandler<FooArgs> FooHappend;
public void Foo()
{
Event.Raise(this, FooHappend, new FooArgs("Hello World!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With