说实话-我问过(这个问题的一部分)here 但现在我有一个不同的相关问题。
public class Base
{
public void Foo(IEnumerable<string> strings) { }
}
public class Child : Base
{
public void Foo(IEnumerable<object> objects) { }
}
List<string> lst = new List<string>();
lst.Add("aaa");
Child c = new Child();
c.Foo(lst);
(n C# 3 它将调用:Base.Foo
在 C# 4 中它将调用:Child.Foo
)
我在 FW4 中! ,让我们谈谈吧
尊重协方差:
当我写 c.Foo(lst);
(lst
是 STRING 的 IEnumerable
!)-
它看到两个 签名!!!但仍然 - 它选择 IEnumerable<object>
??
协方差是否比具体类型本身更强?
最佳答案
这不是因为协方差更强,而是因为C#先选择了“更接近”的方法。因此,它查看 Child.Foo()
,确定它适用(由于协方差)并且甚至不查看 Base.Foo()
。
这里的假设是特定类型“知道”更多,因此应该首先考虑它的方法。
请参阅 C# 4 规范的 §7.6.5.1:
The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F in the set, where C is the type in which the method F is declared, all methods declared in a base type of C are removed from the set.
关于c# - 协方差胜过具体类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462021/