c# - .NET 4.0 中的协变和逆变错误

标签 c# delegates .net-4.0 covariance

C# 4.0 协变和逆变支持的一些奇怪行为:

using System;

class Program {
  static void Foo(object x) { }
  static void Main() {
    Action<string> action = _ => { };

    // C# 3.5 supports static co- and contravariant method groups
    // conversions to delegates types, so this is perfectly legal:
    action += Foo;

    // since C# 4.0 much better supports co- and contravariance
    // for interfaces and delegates, this is should be legal too:
    action += new Action<object>(Foo);
  }
}

ArgumentException: Delegates must be of the same type. 的结果

很奇怪,不是吗?为什么 Delegate.Combine() (在对委托(delegate)执行 += 操作时调用)不支持运行时协变和逆变?

此外,我发现 BCL 的 System.EventHandler<TEventArgs>委托(delegate)类型在其泛型上没有逆变注释 TEventArgs范围!为什么?这是完全合法的,TEventArgs仅在输入位置使用的类型。也许没有逆变注释,因为它很好地隐藏了 Delegate.Combine() 的错误。 ? ;)

附注所有这些都会影响 VS2010 RC 及更高版本。

最佳答案

长话短说:委托(delegate)组合在方差方面一团糟。我们在周期的后期发现了这一点。我们正在与 CLR 团队合作,看看我们是否可以想出一些方法来使所有常见场景工作而不破坏向后兼容性等,但无论我们想出什么,都可能不会进入 4.0 版本。希望我们能在某个服务包中解决所有问题。对于给您带来的不便,我深表歉意。

关于c# - .NET 4.0 中的协变和逆变错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2306814/

相关文章:

.net-4.0 - 无法在 WinDbg 中加载 SOS

c# - Linq to xml,检索基于通用接口(interface)的列表

c# - 获取哈希码(对象): why in some cases it's designed with an argument?

c# - 在后台运行任务但在 ASP MVC Web 应用程序中返回响应给客户端

swift - 尝试通过委托(delegate)方法更新 tableview 时出现弱和委托(delegate)失败警告

asp.net - 为什么在调试 Web 应用程序时会收到 "The server committed a protocol violation Section-ResponseStatusLine"?

c# - 使用延迟进行请求限制有哪些缺点(C# .Net 4 Web Server)

c# - 如何使用 Discord.NET 配置 Discord 角色权限?

c# - 从通用委托(delegate)函数中获取参数类型

ios - 如何将数据从表单 FormSeetController 传递到 ViewController?