首页 > 解决方案 > 可以将子类添加到列表中吗在 C# 中?

问题描述

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

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()
};

这会起作用还是必须为各个子类定义一个列表?

标签: c#.netlisttypescollections

解决方案


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

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


推荐阅读