c#中的协方差

Son*_*oul 19 c# casting covariance

是否有可能投下List<Subclass>List<Superclass>在C#4.0?

这些方面的东西:

class joe : human {}

List<joe> joes = GetJoes();

List<human> humanJoes = joes;
Run Code Online (Sandbox Code Playgroud)

这不是协方差的意思吗?

如果你能做到:

human h = joe1 as human;
Run Code Online (Sandbox Code Playgroud)

你为什么不能这样做

List<human> humans = joes as List<human>; 
Run Code Online (Sandbox Code Playgroud)

因为那个项目已经被贬低了,所以做人类[0]是不合法的,每个人都会很高兴.现在唯一的选择是创建一个新的List

Jon*_*eet 26

你不能这样做,因为它不安全.考虑:

List<Joe> joes = GetJoes();    
List<Human> humanJoes = joes;
humanJoes.Clear();
humanJoes.Add(new Fred());
Joe joe = joes[0];
Run Code Online (Sandbox Code Playgroud)

显然,最后一行(如果不是较早的那一行)必须失败 - 因为Fred它不是一个Joe.List<T>编译时防止此错误而不是执行时间的不变性.


Paw*_*sen 6

实例化一个以joes为输入的新人员列表:

List<human> humanJoes = new List<human>(joes);
Run Code Online (Sandbox Code Playgroud)