c# - 将泛型委托(delegate)转换为具有接口(interface)的另一种类型

标签 c# generics casting delegates xna

(使用.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);
    }

我正在尝试将委托(delegate)存储在一个通用集合中,以便稍后可以将其拉回以调用它。 我该如何正确转换它?

最佳答案

Action 委托(delegate)的通用参数是类型逆变的;它们不是类型协变的。因此,您可以传入一个不太特定的类型,但不能一个更多特定的类型。

所以编译:

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

void Foo(object s) { }

但这不是:

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

void Foo(string s) { }

由于 T 和 U : IMyInterface,您的代码类似于第一个示例。

intellisense 解释得很清楚:(这里是一个 bigger version )

enter image description here

关于c# - 将泛型委托(delegate)转换为具有接口(interface)的另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813174/

相关文章:

c++ - 安全地将 2 个字节转换为短字节

c# - 消息框弹出不止一次

c# - 如何从子表单引用表单?

c# - 测试 WCF URL 的可用性

java - 将泛型类型从一个类传递到另一个类?

c# - IList<变量类型>;不用泛型解决

javascript - 如何创建一个扩展 React.Component 的 BaseClass,以便我的所有其他类都扩展 BaseClass 并可以指定自己的 Props 和 State 类型?

Haskell 求完美平方——出现类型错误

oop - 将子类转换为父类

c# - IHttpHandler 空 session (在某些服务器上)