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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是结果 ArgumentException: Delegates must be of the …
这种限制的真正原因是什么?这只是必须完成的工作吗?概念上难吗?这不可能吗?
当然,人们不能在字段中使用类型参数,因为它们总是读写.但这不是答案,可以吗?
这个问题的原因是我在C#4上写了一篇关于方差支持的文章,我觉得我应该解释为什么它仅限于委托和接口.只是为了逆转举证责任.
更新: 埃里克问了一个例子.
怎么样(不知道这是否有意义,但是:-))
public class Lookup<out T> where T : Animal {
public T Find(string name) {
Animal a = _cache.FindAnimalByName(name);
return a as T;
}
}
var findReptiles = new Lookup<Reptile>();
Lookup<Animal> findAnimals = findReptiles;
Run Code Online (Sandbox Code Playgroud)
在一个类中拥有它的原因可能是类本身中保存的缓存.请不要将您的不同类型的宠物命名为相同!
顺便说一句,这让我想到了C#5.0中的可选类型参数 :-)
更新2:我没有声称CLR和C#应该允许这个.只是想了解是什么原因导致它没有.