协方差在C# [英] covariance in c#
问题描述
是否有可能蒙上了列表<子类化>
到列表<超类>
在C#4.0吗?
Is it possible to cast a List<Subclass>
to List<Superclass>
in C# 4.0?
沿着这些路线的内容:
class joe : human {}
List<joe> joes = GetJoes();
List<human> humanJoes = joes;
这不是什么协方差是?
Isn't this what covariance is for?
如果你可以这样做:
human h = joe1 as human;
为什么你不应该是能够做到
why shouldn't you be able to do
List<human> humans = joes as List<human>;
比它不会是合法的情况(JOE)人类[0],因为该项目已下降铸造..和每个人都会很高兴。现在唯一的方法是创建一个新的List
than it wouldn't be legal to do (joe)humans[0] because that item has been down casted.. and everyone would be happy. Now the only alternative is to create a new List
推荐答案
您不能做到这一点,因为它不会是安全的。试想一下:
You can't do this, because it wouldn't be safe. Consider:
List<Joe> joes = GetJoes();
List<Human> humanJoes = joes;
humanJoes.Clear();
humanJoes.Add(new Fred());
Joe joe = joes[0];
很明显,最后一行(如果不是更早的一个)的的的失败 - 作为一个弗雷德
不是乔
。 清单1所述的不变性; T&GT;
prevents这个错误在编译的时间,而不是执行时间
Clearly the last line (if not an earlier one) has to fail - as a Fred
isn't a Joe
. The invariance of List<T>
prevents this mistake at compile time instead of execution time.
这篇关于协方差在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!