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

发布于 2024-11-10 11:27:35 字数 185 浏览 3 评论 0原文

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

我正在使用 ASP.NET MVC3,并创建了一个包含姓名、年龄等属性的基本模型类。现在我已经创建了包含更多细节的子模型(子类)。 为了轻松处理子类,我想要一个包含其中对象的列表,但如何处理?

我读过有关接口或 ICollection 等的内容,但不知道什么是正确的选择以及如何开始:-(

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

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彡翼 2024-11-17 11:27:35

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

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

然后像平常一样添加子类对象:

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

等等。其中:

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

然后当您将它们取出时,您可以使用 isas运算符来确定它们实际上是什么类型并适当地处理它们。

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

etc. where:

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

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.

稚然 2024-11-17 11:27:35

List<BaseClass>

推荐

class Derived1 : BaesClass {}
class Derived2 : BaesClass {}

I'd recommend

List<BaseClass>

for

class Derived1 : BaesClass {}
class Derived2 : BaesClass {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文