c# - 不同固件中的协方差导致代码中断?

标签 c# inheritance .net-4.0 covariance

我看了 Jon Skeet 在 NDC 2010 上的演讲

他提到了一些有趣的事情:

public Class Base
{
 public void Foo(IEnumerable<string> strings){}
}

public Class Child:Base
{
 publc void Foo(IEnumerable<object> objects) {}
}

Main :

List<string> lst = new List<string>();
lst.Add("aaa");
Child c = new Child();
c.Foo(lst);

使用 C# 3 它将调用:Base.Foo

使用 C# 4 它将调用:Child.Foo

我知道这是因为协方差

问题:

这不是有点破坏代码的变化吗? 是否有任何解决方法可以让此代码继续像在版本 3 上一样工作?

最佳答案

是的,这是一个重大变化。任何时候您使先前无效的转换合法,这都是一个重大更改。

不幸的是,如果不进行任何重大更改,就很难向该语言添加功能。如果您真的想要查找它们,C# 4 中还有一些周围事件。当然,这些不太可能影响大多数开发人员。

C# 1 和 C# 2 之间也有类似的重大变化,其中使用的实现会在这段代码的不同版本之间发生变化:

using System;

public delegate void StringAction(string x);

public class Base
{
    public void Foo(string x)
    {
        Console.WriteLine("Base");
    }
}

public class Child : Base
{
    public void Foo(object x)
    {
        Console.WriteLine("Child");
    }
}

public class Test
{
    static void Main()
    {
        Child c = new Child();
        StringAction action = new StringAction(c.Foo);
        action("x");
    }
}

在这种情况下,编译器实际上会给出警告:

Test.cs(26,31): warning CS1707: Delegate 'StringAction' bound to
        'Child.Foo(object)' instead of 'Base.Foo(string)' because of new
        language rules

关于c# - 不同固件中的协方差导致代码中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9335278/

相关文章:

Java 泛型 : compatible service subclass

c# - 避免在锁内和锁外重复if语句

.net-4.0 - 关于 .NET 4.0 Workflow Foundation 中的 Argument<T> 和 Variable<T> 的混淆

c# - 为嵌套属性实现 INotifyPropertyChanged

c# - 如何正确使用C#接口(interface)?

c# - 正确的 Join/GroupJoin 实现

C++:覆盖纯虚拟成员变量?

java - 我需要知道控制流是什么以及这段代码到底发生了什么?

c# - 无法加载文件或程序集 antlr.runtime

c# - Silverlight DependencyProperty问题