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

久未见 提交于 2019-12-31 00:45:18

问题


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 :-(


回答1:


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.




回答2:


I'd recommend

List<BaseClass>

for

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


来源:https://stackoverflow.com/questions/6194482/how-can-i-put-subclasses-from-the-same-baseclass-into-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!