dimanche 26 août 2018

Get Base Class Event Delegates by Reflection

I need to get all Delegates which are subscribed to events in an object. The object is instantiated from a class which inherits a base class. I can get all Delegates for events defined in the class, but not for the ones of the base class.

So, in code, here's what I have in principle (I don't copy declarations etc. to keep it short):

public class DerivedClass : Base Class
{
    public event EventHandler<UserDefinedEventArgs> DerivedClassEvent;
    [...]        
}

The Base class is defined like this (hosting the functions for getting the Delegates I need):

public abstract class BaseClass 
{
    public event EventHandler<UserDefinedEventArgs> BaseClassEvent;

    public Dictionary<EventInfo, List<Delegate>> getAllEventsSubscribersList()
    {

        EventInfo[] eventInfoS = this.GetType().GetEvents(); //Get all events / event infos defined in the class

        foreach (EventInfo eventInfo in eventInfoS)
        {
            resDelegates = this.getEventSubscriberList(eventInfo); //Get the delegates for each event
        }
    }

    public List<Delegate> getEventSubscriberList(EventInfo eventInfo)
    {
        FieldInfo eventFieldInfo = this.GetType().GetField(eventInfo.Name, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);

        Delegate eventFieldValue = (System.Delegate)eventFieldInfo.GetValue(this);

        Delegate[] subscribedDelegates = eventFieldValue.GetInvocationList();
    }
}

Then, I try to get all events and their Delegates like this:

DerivedClass myObject = new DerivedClass();
Dictionary<EventInfo, List<Delegate>> EventAndDelegatesList = myObject.getAllEventsSubscribersList();

When calling 'getAllEventsSubscribersList', all events of the derived as well as of the base class are found correctly. But in the function for retreiving the actual Delegates, the FieldInfo for the "BaseClassEvent" is always 'null'.

How can I read the delegates for the base class event?





Aucun commentaire:

Enregistrer un commentaire