c# - 协方差胜过具体类型?

标签 c# inheritance .net-4.0 covariance

说实话-我问过(这个问题的一部分)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/

相关文章:

保存多个图像后 C# GDI+ 一般错误/外部异常

c# - 平滑曲线的算法

c++ - 部分隐藏的继承树

.net - Web 服务器上 Reporting Services 2005 到 .NET 4 框架的问题

c# - VSTO PowerPoint/Excel 交互

c++ - 删除 std::unique_ptr<Base> 容器中的派生类

java - 如何从父类(super class)类型的ArrayList中获取某个子类型的对象?

dll - 如何集中 VB6 dll 引用的 .net dll(com 互操作)

wpf - 如何从Task更新CollectionViewSource的Source属性?

引号内的 C# 变量