使用不同类型但使用通用方法调用对象中的方法

时间:2015-10-28 14:28:26

标签: c# events

我在静态类中有一个方法,它提供对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;

1 个答案:

答案 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重写为publisherpublisher as publisherName也不会编译。如果您的object publisherEventHandler,例如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);
}