关于C#的协方差问题 [英] Question about C# covariance

查看:92
本文介绍了关于C#的协方差问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的code:

interface I1 { }
class CI1: I1 { }

List<CI1> listOfCI1 = new List<CI1>();

IEnumerable<I1> enumerableOfI1 = listOfCI1; //this works

IList<I1> listofI1 = listOfCI1; //this does not

我能够分配我的listOfCI1给的IEnumerable&LT; I1&GT; (由于协方差)

不过,我为什么不能把它分配给了的IList&LT; I1&GT;
对于这个问题,我甚至不能做到以下几点:

But why am I not able to assign it to an IList<I1>? For that matter, I cannot even do the following:

List<I1> listOfI12 = listOfCI1;

不应该方差让我派生类型分配给一个基本类型?

Shouldn't covariance allow me to assign a derived type to a base type?

推荐答案

简而言之,的IList&LT; T&GT; 不是协变的,而的IEnumerable&LT; T&GT; 是。这里的原因...

Simply put, IList<T> is not covariant, whereas IEnumerable<T> is. Here's why...

假设的IList&LT; T&GT; 的协变。下面的code显然不是类型安全的...但你会在哪里希望误差为?

Suppose IList<T> was covariant. The code below is clearly not type-safe... but where would you want the error to be?

IList<Apple> apples = new List<Apple>();
IList<Fruit> fruitBasket = apples;
fruitBasket.Add(new Banana()); // Aargh! Added a Banana to a bunch of Apples!
Apple apple = apples[0]; // This should be okay, but wouldn't be

方差细节

有关的地段的,请参阅埃里克利珀的的博客文章系列的就可以了,或者看我的说说方差NDC的影片

For lots of detail on variance, see Eric Lippert's blog post series on it, or watch the video of my talk about variance from NDC.

基本上,方差永远只能容许它的保证是安全的(并且在重新presentation- preserving方式,这就是为什么你不能转换的IEnumerable&LT; INT&GT; 的IEnumerable&LT;对象&gt; - 拳击转换不会preserve重新presentation)

Basically, variance is only ever allowed where it's guaranteed to be safe (and in a representation-preserving way, which is why you can't convert IEnumerable<int> into IEnumerable<object> - the boxing conversion doesn't preserve representation).

这篇关于关于C#的协方差问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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