协方差在不同的FW导致code打破? [英] Covariance in different FW causes Code Break?

查看:169
本文介绍了协方差在不同的FW导致code打破?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到乔恩斯基特的讲座在NDC 2010

I saw Jon Skeet's lecture at the NDC 2010

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

He mentioned something interesting :

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

With C# 3 it will call : Base.Foo

使用C#4,它会调用: Child.Foo

With C# 4 it will call : Child.Foo

我知道这是因为协方差

问:

是不是有点code重大更改? 有任何解决方法所以这code将继续工作,因为它是在版本3?

Isn't it a bit code breaking change ? Is there any workaround so this code will continue work as it was on ver 3?

推荐答案

是的,这是一个重大更改。任何时候你犯了一个prevously-无效转换的法律,这是一个重大更改。

Yes, it's a breaking change. Any time you make a prevously-invalid conversion legal, it's a breaking change.

不幸的是,这是非常困难的特性添加到语言未做的任意的重大更改。如果你的周边有活动多了一些在C#4真的的想看看他们。这是不可能的,这些都会影响当然,大多数开发商。

Unfortunately, it's very hard to add features to the language without making any breaking changes. There are a few more around events in C# 4 if you really want to look for them. It's unlikely that these will affect most developers, of course.

在一些情况中使用的实施将有不同的版本之间改变了这个code C#1和C#2之间类似的重大更改:

There were similar breaking changes between C# 1 and C# 2, where the implementation used would have changed between different versions for this code:

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");
    }
}

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

In this case the compiler actually gives a warning:

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

这篇关于协方差在不同的FW导致code打破?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆