如何使用动态参数类型创建委托?

时间:2014-12-12 13:52:16

标签: c# windows-phone

我有一个EventHandler类型的委托对象< AsyncCompletedEventArgs >我想将此对象添加到EventHandler类型的事件< T >我知道类型 T总是扩展AsyncCompletedEventArgs 。 我尝试做的事情有点像这样:

public static void AssignDelegate(this ICommunicationObject client, string eventName) 
{
    EventInfo eventInfo = client.GetType().GetEvent(eventName);
    EventHandler<AsyncCompletedEventArgs> eventHandler = (object o, AsyncCompletedEventArgs e) => 
    {
        // Some generic code that will be used as a handler to all events
    }    

    // I want be able to add the eventHandler to the eventInfo using the 
    // AddEventHandler method, but this does not seem possible since this 
    // event accepts delegates of type EventHandler<SomeClassThatExtendsAsyncCompletedEventArgs>
    // (It probably would if the EventHandler generic argument was contravariant)
    eventInfo.AddEventHander(client, eventHandler);
}

还有其他办法吗?也许在运行时更改参数e的类型?

1 个答案:

答案 0 :(得分:1)

你可以通过反思来做到这一点:

// your global handler, it can be regular method
private static void GlobalEventHandler(object o, AsyncCompletedEventArgs e)
{
    Console.WriteLine(e.GetType());
}

// your extension method
public static void AssignDelegate(this object client, string eventName)
{
    // get event
    EventInfo eventInfo = client.GetType().GetEvent(eventName);
    // get build handler method
    MethodInfo buildHandlerMethod = MethodInfo.GetCurrentMethod().DeclaringType.GetMethod("BuildHandler");
    // get type of arg; 
    // eventInfo.EventHandlerType is EventHandler<T>, where T: AsyncCompletedEventArgs, 
    // so we are interested in T
    Type argType = eventInfo.EventHandlerType.GetGenericArguments()[0];

    // add handler
    eventInfo.AddEventHandler(client, (Delegate)buildHandlerMethod.MakeGenericMethod(argType).Invoke(null, null));
}

// method which returns proper handler for event, 
// it delegates invocation to GlobalEventHandler
public static EventHandler<T> BuildHandler<T>() where T : AsyncCompletedEventArgs
{
    return GlobalEventHandler;
}