![](/img/trans.png)
[英]How can I get a list of the underlying delegates from an event using reflection?
[英]Get Base Class Event Delegates by 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”。
如何阅读基类事件的委托?
事件就像是委托的自动实现的属性。 您还可以显式声明它。 这将允许您将事件处理程序插入您选择的集合中
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.
}
}
也可以看看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.