【问题标题】:Can a Child Class be Added to a List<Parent> in C#?可以将子类添加到 C# 中的 List<Parent> 中吗?
【发布时间】:2021-11-17 23:19:40
【问题描述】:

在我的项目中,我有几个类继承自一个父类。我想定义一个列表,其中包含每个子类的对象。

public class Parent
{
    public string name;
}

public class Child1 : Parent
{
    public int property1;
}

public class Child2 : Parent
{
    public int property2;
}

public List<Parent> childrenOfParent = new List<Parent>(){
    new Child1(),
    new Child2()
};

这是否可行,还是必须为各个子类定义一个列表?

【问题讨论】:

  • 定义这行得通吗。 -- 你只需要name 属性吗?你在你的类中实现了任何接口吗?
  • 你为什么不试试?
  • 如果您不在命名空间中,它会起作用! ??????

标签: c# .net list types collections


【解决方案1】:

是的,这可行,但如果你这样做,你将只能访问父类的方法和属性(除非你添加显式转换),因为当对象被转换为父类的类型时被插入到List

这是根据标准 C# 转换规则,子类对其父类具有隐式转换,如 in the docs 所述。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2019-08-30
  • 2011-03-18
  • 2015-05-06
  • 2017-01-19
相关资源
最近更新 更多