c# - 可以将子类添加到列表中吗在 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()
};
这会起作用还是必须为各个子类定义一个列表?
解决方案
是的,这行得通,但是如果这样做,您将只能访问父类的方法和属性(除非您添加显式转换),因为对象在插入时被转换为父类的类型List
. _
这是根据标准 C# 转换规则,子类对其父类具有隐式转换,如docs 中所述。
推荐阅读
- oracle - 如何在程序中使用is /?
- swift - 在这种情况下,“HTTPMethod”对于类型查找是模棱两可的?
- firebase - 在 Google Analytic 中找不到视图列
- java - 数据库更改时,在先前的字符串键上发生 NumberFormatException
- php - PHP合并数组中的重复键
- ruby - 将新的键值插入到 Ruby 中的嵌套哈希中
- jquery - 动态设置特定单元格的颜色
- python - 在odoo开发中,我每次创建数据的时候,都会出现这样的xml编码错误
- angular - 影响子选项卡的 Mat-Tab 背景颜色
- python - 传递函数+对应参数,作为另一个函数的参数,而传递函数的参数个数不同