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/