简体   繁体   English

如何转换EventHandler <T> 到EventHandler <EventArgs> ?

[英]How to cast EventHandler<T> to EventHandler<EventArgs>?

I'm creating a centralized event aggregator that keeps a registry that accepts EventHandler delegates. 我正在创建一个集中的事件聚合器,该聚合器保留一个接受EventHandler委托的注册表。 The aggregator class itself is not generic, but the register method is: 聚合器类本身不是通用的,但是register方法是:

public void RegisterHandler<T>(EventHandler<T> handler) where T : EventArgs
{
    Debug.Assert(handler != null);
    if (handler != null)
    {
        if (this._eventRegistry != null)
        {
            this._eventRegistry.AddValue(typeof(T), handler);
        }
        else { /* Do nothing. */ }
    }
    else 
    { 
        throw new ArgumentNullException(ReflectionUtilities.GetVariableName(() => handler)); 
    }
}

The aim is to allow registry of any type that derives from EventArgs. 目的是允许从EventArgs派生的任何类型的注册表。 But the registry (a type of Dictionary) accepts EventHandler of type EventArgs and not EventHandler of type T where T is EventArgs. 但是注册表(一种类型的Dictionary)接受EventArgs类型的EventHandler,而不接受T类型的EventHandler,其中T是EventArgs。

The line 线

this._eventRegistry.AddValue(typeof(T), handler);

will not compile because it says it has some invalid arguments (specifically 'handler'). 将不会编译,因为它说它有一些无效的参数(特别是“ handler”)。 If I change that argument to 如果我将参数更改为

this._eventRegistry.AddValue(typeof(T), handler as EventHandler<EventArgs>);

then the code compiles but the argument 'handler' has a null value. 然后代码会编译,但参数'handler'具有空值。

Similarly, if I do this: 同样,如果我这样做:

EventHandler<EventArgs> eventHandler = handler as EventHandler<EventArgs>;

then 'eventHandler' is null. 则'eventHandler'为null。

If I know that T is constrained to be type or subtype of EventArgs, how can I cast 如果我知道T被限制为EventArgs的类型或子类型,该如何转换

EventHandler<T>

to

EventHandler<EventArgs>

?

You can't cast an EventHandler<T> to an EventHandler<EventArgs> . 您不能将EventHandler<T> EventHandler<EventArgs>转换为EventHandler<EventArgs> A somewhat ugly but simple workaround, is to change this line of your code: 一个有点丑陋但简单的解决方法是更改​​代码的这一行:

this._eventRegistry.AddValue(typeof(T), handler);

to

this._eventRegistry.AddValue(typeof(T), (sender, evt) => handler(sender, (T)evt));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM