是否可以将更多不同类型的对象添加到同一个列表中,我该怎么做?
我有一个基类和三个子类,我希望所有子类对象都在同一个列表中。
最佳答案
当然 - 只需使用基本类型作为泛型类型参数创建一个列表:
List<Control> controls = new List<Control>();
controls.Add(new TextBox());
controls.Add(new Label());
controls.Add(new Button());
// etc
请注意,当您再次检索这些项目时,您只会“知道”它们是基本类型,因此如果您想执行任何特定于子类型的操作,您将需要进行转换。例如:
// Assuming you know that there's at least one entry...
Control firstControl = controls[0];
TextBox tb = firstControl as TextBox;
if (tb != null)
{
// Use tb here
}
如果你想获取特定类型(或其子类型)的所有元素,你可以使用OfType<>
方法:
foreach (TextBox tb in controls.OfType<TextBox>())
{
// Use tb here
}
关于c# - 一个列表中具有更多不同类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8478324/