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()
(在对委托执行+=
操作时调用)在运行时不支持协变和逆变?
此外,我发现 BCL 的委托类型在其泛型参数System.EventHandler<TEventArgs>
上没有逆变注释!TEventArgs
为什么?这是完全合法的,TEventArgs
仅在输入位置使用的类型。也许没有逆变注释,因为它很好地隐藏了带有Delegate.Combine()
? ;)
ps 所有这些都会影响到VS2010 RC 及更高版本。