使用接口将泛型委托转换为另一种类型

DJ *_*tiX 3 c# generics xna delegates casting

(使用.NET 4.0)好的,我有

private Dictionary<int, Action<IMyInterface, IMyInterface>> handler {get; set;}

public void Foo<T, U>(Action<T, U> myAction)
    where T : IMyInterface
    where U : IMyInterface
    {
        // | This line Fails
        // V
        Action<IMyInterface, IMyInterface> anotherAction = myAction;
        handler.Add(someInt, anotherAction);
    }
Run Code Online (Sandbox Code Playgroud)

我正在尝试将委托存储在一个泛型集合中,所以我可以稍后将其拉回来调用它.我该如何正确施展它?

Ada*_*kis 7

Action委托的通用参数是类型逆变的; 它们不是类型协变的.其结果是,你可以通过在较少的具体类型,但不是一个具体的类型.

所以这个编译:

protected void X()
{
    Action<string> A = Foo;
}

void Foo(object s) { }
Run Code Online (Sandbox Code Playgroud)

但这不是:

protected void X()
{
    Action<object> A = Foo;
}

void Foo(string s) { }
Run Code Online (Sandbox Code Playgroud)

因为T and U : IMyInterface,您的代码类似于第一个示例.

intellisense相当清楚地解释了它:(这是一个更大的版本)

在此输入图像描述