问题
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 it will call : Base.Foo
in C# 4 it will call : Child.Foo)
Im in FW4 ! , lets talk about it
with all the respect to covariance :
when I write c.Foo(lst); ( lst is IEnumerable of STRING !) -
it sees both signatures !!! but STILL - it chooses IEnumerable<object> ??
does covariance stronger than the concrete type itself ?
回答1:
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.
See §7.6.5.1 of the C# 4 spec:
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.
来源:https://stackoverflow.com/questions/10462021/covariance-beats-concrete-type