C#中的协方差 [英] covariance in c#

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

问题描述

是否可以在 C# 4.0 中将 List 转换为 List?

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;

你为什么不能做

List<human> humans = joes as List<human>; 

因为这样做 (joe)humans[0] 是不合法的,因为该项目已被弃用..每个人都会很高兴.现在唯一的选择是创建一个新列表

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];

显然最后一行(如果不是更早的一行)必须失败——因为 Fred 不是 Joe.List 的不变性可以防止在编译时出现这个错误,而不是在执行时.

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屋!

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