【问题标题】:Casting generic delegated to non generic with the same signature将泛型委托给具有相同签名的非泛型
【发布时间】:2014-03-28 15:17:29
【问题描述】:

这一定是一个简单的问题。我定义了两种委托类型:

delegate void TestHandler(object sender, EventArgs args);
delegate void TestHandlerGen<TArgs>(object sender, TArgs args);

然后我使用它们:

TestHandler h1 = null;
TestHandlerGen<EventArgs> h2 = delegate { };

// this compiles
h1 = new TestHandler(h2);

// this doesn't compile:
// Cannot implicitly convert type 'X.TestHandlerGen<System.EventArgs>' 
// to 'X.TestHandler'
h1 = h2;

代表签名相同,为什么h1 = h2编译不通过?

为什么h1 = new TestHandler(h2) 编译得很好?

【问题讨论】:

    标签: c# generics compiler-construction delegates type-conversion


    【解决方案1】:

    来自规范:

    15.1 委托声明

    C# 中的委托类型是名称等价的,而不是结构上等价的。 具体来说,两个不同的委托类型具有相同的 参数列表和返回类型被认为是不同的委托 类型

    第一个示例有效,因为您可以从兼容的委托实例创建新委托。所以虽然h2h1 兼容,但它们并不相等,因为它们有不同的类型:

    7.6.10.5 委托创建表达式

    委托创建表达式用于创建一个新的实例 委托类型。委托创建表达式:

    新的委托类型(表达式)

    委托创建表达式的绑定时处理 形成 newD(E),其中 D 是委托类型,E 是表达式, 由以下步骤组成:

    • 如果 E 是一个值,则 E 必须与 D 兼容(第 15.1 节),并且结果 是对新创建的 D 类型委托的引用,该委托引用 与 E 相同的调用列表。如果 E 与 D 不兼容,则 发生编译时错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      相关资源
      最近更新 更多