Say I have a class just for specifying C# events and I pass this class around my application.
public class MyEvents
{
public event MyEventHandler OnBeforeSomeAction;
public event MyEventHandler OnSomeAction;
}
In order to invoke these events the invocation has to come from within the class itself. The easy way to let other classes trigger these events as MyEvents gets passed around the application would be to create public trigger functions.
public class MyEvents
{
public event MyEventHandler OnBeforeSomeAction;
public event MyEventHandler OnSomeAction;
public void TriggerOnBeforeSomeAction()
{
OnBeforeSomeAction();
}
public void TriggerOnSomeAction()
{
OnSomeAction();
}
}
However, if there are many events on this class then there would also have to be many trigger methods. Would there be a way to get the event using reflection and trigger it? Something like this:
public class MyEvents
{
public event MyEventHandler OnBeforeSomeAction;
public event MyEventHandler OnSomeAction;
public void TriggerEvent(string eventName)
{
var event = // some magic reflection.
event.Invoke();
}
}
Exactly what you want – taken from this fantastic page….