合作和逆变错误在.NET 4.0中逆变、错误、NET

由网友(深拥必伤。)分享简介:一些奇怪的行为与C#4.0合作和逆变支持:Some strange behavior with the C# 4.0 co- and contravariance support:using System;class Program {static void Foo(object x) { }static void...

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

Some strange behavior with the C# 4.0 co- and contravariance support:

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:代表必须是同一类型的

奇怪,不是吗?为什么 Delegate.Combine()(表演代表 + = 操作时,它被调用)不支持合作 - ?和逆变运行时

Strange, isn't it? Why Delegate.Combine() (which is been called when performing += operation on the delegates) does not support co- and contravariance at runtime?

此外,我发现,BCL的 System.EventHandler&LT; TEventArgs&GT; 委托类型不具有逆变诠释它的通用 TEventArgs 参数!为什么?这是完全合法的, TEventArgs 键入只在输入位置使用。也许没有逆变注解,因为它很好地隐藏了错误的 Delegate.Combine()? ;)

Moreover, I've found that BCL's System.EventHandler<TEventArgs> delegate type does not has contravariant annotation on it's generic TEventArgs parameter! Why? It's perfectly legal, TEventArgs type used only at input position. Maybe there is no contravariant annotation because of it nicely hides the bug with the Delegate.Combine()? ;)

P.S。所有这一切都影响了VS2010 RC和更高版本。

p.s. All this affects the VS2010 RC and later versions.

推荐答案

长话短说:委托相结合的的全乱了的相对变化。我们发现了这个迟到的周期。我们正在与CLR的团队合作,看看我们是否能够想出一些办法使所有的常见方案的工作不打破向后兼容性,等等,但无论我们拿出大概不会让它到4.0版本。希望我们能让这一切整理出一些服务包。我带来的不便表示歉意。

Long story short: delegate combining is all messed up with respect to variance. We discovered this late in the cycle. We're working with the CLR team to see if we can come up with some way to make all the common scenarios work without breaking backwards compatibility, and so on, but whatever we come up with will probably not make it into the 4.0 release. Hopefully we'll get it all sorted out in some service pack. I apologize for the inconvenience.

阅读全文

相关推荐

最新文章