我有一个要求,以增加不同类型的对象(即使它们是不同的,它们共享相同的基类,它们是兄弟姐妹。我怎么可以在不同类型的对象存储在C#泛型列表
考虑这个类层次
public abstract class Fruit
{
public int Quality { get; set; }
public string Name { get; set; }
}
public sealed class Apple :Fruit
{
public string Color { get; set; }
public Apple(string color ="Red")
{
Color = color;
}
}
public sealed class Orange : Fruit
{
public Orange(string type = "WithSeed")
{
Type = type;
}
public string Type { get; set; }
}
我怎样才能做这样的事情
_apples = new List<Apple>
{
new Apple
{
Name = "Fiji Apple",
Quality = 9,
Color ="Green"
},
new **Orange**
{
Name = "Indi Orange",
Quality = 7,
}
};
这个泛型列表的消费者会使用它使用的基类,例如:使用IEnumerable<Fruit>
。 有人可以建议吗?
可以在不使用基类的情况下完成。我的意思是说,即使不同类型的物体(苹果,橙子,菠萝等)被传递来准备这个数组,它们也应该被视为苹果。 – ViBi
我不知道在这方面“投射”是什么意思。你是否希望软件根据你对橙色的描述来组成苹果?橙色没有颜色属性,所以它怎么能做到这一点?你不能混合苹果和橙子;) –
你会如何将橙色作为一个苹果? “Apple”有一大堆“Orange”没有的东西,反之亦然。您将不得不创建一个新的Apple对象,该对象尽可能与原始的“Orange”对象共享,但是您将失去对原始对象的引用以及所有“Orange”特定信息。 – Abion47