如何将相同基类的子类放入列表中? [英] How can I put subclasses from the same baseclass into a list?

查看:120
本文介绍了如何将相同基类的子类放入列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将相同基类的子类放入列表中?

How can I put subclasses from the same baseclass into a list?

我正在使用ASP.NET MVC3,并创建了具有名称,年龄等属性的基本模型类.现在,我创建了具有更多详细信息的子模型(子类). 为了轻松处理子类,我想要一个包含对象的列表,但是如何呢?

I´m working with ASP.NET MVC3 and have created a basemodel-class with properties like name, age and so on. Now i have created submodels (subclasses) with more details. To easily handle the subclasses i want a list with the objects in it but how?

我已经阅读了有关接口或ICollection等的信息,但不知道什么是正确的选择以及如何开始:-(

I have read about interfaces or ICollection and so on but don´t know what´s the right choice and how to start :-(

推荐答案

只需创建列表,使其属于基类:

Just create the list so it's of the base class:

List<BaseClass> myList = new List<BaseClass>();

然后正常添加子类对象:

then add your subclass objects as normal:

myList.Add(new SubClass1());
myList.Add(new SubClass2());

等其中:

public class SubClass1 : BaseClass {}
public class SubClass2 : BaseClass {}

然后,当您找到它们时,可以使用isas运算符来确定它们实际是什么类型并适当地处理它们.

Then when you get them out you can use the is and as operators to determine what type they actually are and deal with them as appropriate.

这篇关于如何将相同基类的子类放入列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆