将继承的项添加到同一个列表容器中

时间:2014-04-02 05:57:02

标签: c# list oop

伙计我不确定我是否缺少任何重要的OOP概念,请指导我如果我遗失了什么。 我有一个基类和一些继承的类,如下所示

Class Shape {}
Class Arc:Shape{}
Class Line:Shape{}

现在我想制作一个所有生成的形状的容器(List),然后当我回读时,我会将对象转换为特定类型。什么是最好的方法。仿制药是我在下面显示的唯一方法?请帮忙

SortedList shapeList;
public int addShapes(Shape item)  {shapeList.Add(ItemID, item);}

2 个答案:

答案 0 :(得分:3)

您可以将所有Shape个实例放入List<Shape>

var list = new List<Shape>();
list.Add(new Arc());
list.Add(new Line());
list.Add(new Arc());
list.Add(new Arc());
list.Add(new Line());

要获取所有Arc个实例,您可以执行以下操作:

var arcs = list.OfType<Arc>();

,类似地,对于所有Line个实例:

var lines = list.OfType<Line>();

答案 1 :(得分:1)

将您的对象添加到List<Shape>

var list = new List<Shape>();
list.Add(new Arc());
list.add(new Line());
list.Add(new Arc());

然后使用LINQ查询原始列表并检索对象:

var arcList = list.Where(x => x.GetType() == typeof(Arc)).ToList();
相关问题