指定派生类集合基类集合编译错误 [英] Assign Derived Class Collection to Base Class Collection compilation error

查看:246
本文介绍了指定派生类集合基类集合编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班

class Base
{

}
class Derived : Base
{

}

基地基地=新派生的(); 没有编译错误

如果我这样做的ICollection<基地> collBase =新的List<衍生GT;(); 它给人的编译错误。是否有任何其他的替代品来解决这个

if I do ICollection<Base> collBase = new List<Derived>(); it gives the compilation error. Is there any other alternatives to solve this?

推荐答案

如果您使用的是.NET版本4:更改的ICollection来的IEnumerable

If you are using .Net version 4 : Change ICollection to IEnumerable

http://msdn.microsoft .COM / EN-US /库/ dd799517.aspx

编辑 - 更多有用的阅读

Edit - more useful reading

http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx

试图进一步明确为什么你不能做到这一点:

attempting to clarify further why you can't do this:

class animal {}
class dog : animal {}
class cat : animal {}

ICollection<animal> dogs = new List<dog>(); //error (Or List<T>, same error) because...
dogs.Add(new cat()); //you just dogged a cat

IEnumerable<animal> dogs = new List<dog>(); // this is ok!

这篇关于指定派生类集合基类集合编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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