是honest- IVE问(这个问题的一部分)here 但现在我有一个不同的 - 有关的问题
to be honest- ive asked (a part of this question) here but now i have a different - related question.
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
)
(n C# 3 it will call : Base.Foo
in C# 4 it will call : Child.Foo
)
即时消息在FW4! ,让我们来谈谈它的
所有的关于协方差:
当我写 c.Foo(LST); LST
(是
的IEnumerable
字符串的) - !
with all the respect to covariance :
when I write c.Foo(lst);
( lst
is IEnumerable
of STRING !) -
它看到的两个的签名!但还是 - 它选择的IEnumerable&LT;对象&gt;
??
it sees both signatures !!! but STILL - it chooses IEnumerable<object>
??
确实比协的具体类型本身更强?
does covariance stronger than the concrete type itself ?
这是不是因为方差是强,但因为C#选择了更紧密的方法第一。因此,它着眼于 Child.Foo()
,决定它适用(感谢协方差),甚至不看 Base.Foo( )
。
This is not because covariance is stronger, but because C# chooses the "closer" method first. So, it looks at Child.Foo()
, decides it is applicable (thanks to covariance) and doesn't even look at Base.Foo()
.
这里的假设是,特定类型的知道多,所以它的方法应首先考虑
The assumption here is that specific type "knows" more, so its methods should be considered first.
查看C#4规范的§7.6.5.1:
See §7.6.5.1 of the C# 4 spec:
的候选方法集被减少到仅包含派生程度最大的类型,只有方法:对于该集中,其中C是其中方法F的声明的类型的每个方法CF,所有的方法中的C基类中声明从集合中移除。
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.