I am trying to dynamically assign event handlers in c#. For this, I am looking for a solution to get all subscribers for an event, without knowing the exact type (since I have a generic hosting logic for the classes throwing events).
Overall, I have the following setting (simplified to the event part). There is a base class, providing a function to deliver all handlers of all events:
class BaseClass {
public System.Delegate[] getHandlers(EventHandler GenericEvent) {
return GenericEvent.GetInvocationList();
}
}
This Basic class then is derived (multiple times) in the following way:
class DerivedClassOne : BaseClass {
public event EventHandler<CustomEventArgsClass1> CustomClassOneEvent;
[...]
}
class DerivedClassTwo : BaseClass {
public event EventHandler<CustomEventArgsClass2> CustomClassTwoEvent;
[...]
}
Now, I want to get all Handlers assingned to the events in an object of Type One or Two. With the following code I can get all event types / infos:
DerivedClassOne c1 = new DerivedClassOne();
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
Type myTypeEvent = c1.GetType();
EventInfo[] myEventsBindingFlags = myTypeEvent.GetEvents(myBindingFlags);
Now, with event.GetInvocationList() I can get all Handlers for an event - at least inside the derived class:
System.Delegate[] handler = CustomClassOneEvent.GetInvocationList();
What I want to achieve is to have a routine inside the base class to provide the handlers for an event type, something like this:
public System.Delegate[] getHandlers(EventHandler GenericEvent) {
return GenericEvent.GetInvocationList();
}
So, two main questions:
- How do I get the "GenericEvent" based on the EventInfo I have?
- Is it even possible to have this routine in the base class, or can't I access the events defined in the derived classes then?
Aucun commentaire:
Enregistrer un commentaire