【问题标题】:Holding derived class list objects in Base class list object [duplicate]在基类列表对象中保存派生类列表对象[重复]
【发布时间】:2015-12-23 20:10:20
【问题描述】:

如何在基类列表对象中保存派生类列表对象

class Base 
{
}

class Child : Base 
{
}

Base obj = new Child();

对于列表是否同样有效。

List<Base> obj = new List<Child>(); 

这给了我错误,实现这一目标的最佳方法是什么。

【问题讨论】:

  • 下一行:obj.Add(new SomeOtherClassInheritingFromBaseThatIsntChild()) - 你看到问题了吗?

标签: c# oop inheritance


【解决方案1】:

仅仅因为 ChildBase 具有隐式转换,并不意味着 List&lt;Child&gt;List&lt;Base&gt; 这样做,因为它们现在是 List&lt;&gt; 对象。

List<Base> = (List<Base>)(new List<Child>())

您需要将子列表转换为父列表。

【讨论】:

  • 那个演员阵容不行。
  • 你是对的。他必须自己定义吗?
猜你喜欢
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 2011-01-05
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
相关资源
最近更新 更多