通过反射获取基类事件委托

时间:2018-08-26 19:42:23

标签: c# inheritance events reflection

我需要获取已预订对象中事件的所有代表。从继承基类的类实例化该对象。对于类中定义的事件,我可以获取所有委托,但是对于基类中的事件,则不能。

所以,在代码中,这是我的原则(我不复制声明,值聚合和返回等以使其简短):

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

基类的定义如下(托管用于获取我需要的代表的函数):

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();
    }
}

然后,我尝试按以下方式获取所有事件及其代表:

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

在调用“ getAllEventsSubscribersList”时,可以正确找到派生类和基类的所有事件。 但是在获取实际委托的函数中,“ BaseClassEvent”的FieldInfo始终为“ null”。

我如何阅读基类事件的委托人?

1 个答案:

答案 0 :(得分:0)

事件就像是委托的自动实现的属性。您还可以显式声明它。这将允许您将事件处理程序插入您选择的集合中

public event EventHandler<UserDefinedEventArgs> DerivedClassEvent
{
    add
    {
        // TODO: add the event handler to a collection and subscribe it to a hidden delegate.
    }
    remove
    {
        // TODO: remove the event handler from the collection and unsubscribe it.
    }
}

另请参见