我在静态类中有一个方法,它提供对eventHandler的引用,以便它可以跟踪其中的订阅者数量。可以有许多事件处理程序,但它们都有'GetInvocationList()'方法。那么,我如何在不同类型的对象上调用'GetInvocationList()'方法。
static class EventTracker
{
public static ArrayList arrayList1;
static EventTracker()
{
arrayList1 = new ArrayList();
}
public static void AddRecord(String publisherName, object publisher)
{
arrayList.Add((publisher as publisherName).GetInvocationList().Length); //doesnot work
}
}
这些是调用方法。
EventTracker.AddRecord("SelectionAwareEventHandler", SelectionChanged);
EventTracker.AddRecord("NumberChangedEventHandler", NumberChanged);
以下是如何定义事件处理程序
public event SelectionAwareEventHandler SelectionChanged;
public event NumberChangedEventHandler NumberChanged;
答案 0 :(得分:0)
假设您有一个非类型化的事件处理程序引用,如
object publisher = ...;
MethodInfo getInvocationListMethod = publisher.GetType().GetMethod("GetInvocationList");
// call the method
Delegate[] invocationList = (Delegate[])getInvocationListMethod.Invoke(publisher, null);
int length = invocationList.Length;
您还可以将AddRecord
方法重写为不使用object
,而delegate
重写为publisher
。 publisher as publisherName
也不会编译。如果您的object publisher
是EventHandler
,例如delegate
您根本不需要发布商名称,因为为GetInvocationList
EventHandler
public static void AddRecord(delegate publisher)
{
arrayList.Add(publisher.GetInvocationList().Length);
}
如果您确定publisher
始终是delegate
,请将您的object publisher
转换为delegate
public static void AddRecord(object publisher)
{
arrayList.Add((publisher as Delegate).GetInvocationList().Length);
}