Covariance beats concrete type?

二次信任 提交于 2019-12-07 09:46:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!