包含继承类的基类的C#数组,访问非继承字段

时间:2018-12-13 06:35:26

标签: c# arrays class inheritance abstract-class

我有一个抽象类Detail,还有四个类扩展了Detail。Rock,Grass,Tree和Bush。

树和布什拥有水果属性,而其他则没有

我有一个Detail [],其中包含所有4种类型的细节,并且给定索引,我需要找到该细节的果实(如果有的话)。

我不想将Fruit属性放在基类Detail中,因为并非所有细节都具有水果,并且不同种类的细节具有完全不同的属性。

如何获取例如Detail [17]之类的Fruit,而无需事先知道它的详细类型,或者它是否有结果(如果没有,则返回null)?请记住,可能会有数百种不同类型的细节以及数十种可能的属性。

我正在想象一种标签系统,其中数组中的每个项目可能具有也可能没有多个标签之一,但这是我到目前为止管理的最接近的标签。

2 个答案:

答案 0 :(得分:4)

使TreeBush以及其他具有Fruit属性的子类实现IHasFruit,如下所示:

interface IHasFruit {
    // I assume "Fruit" properties are of type "Fruit"?
    // Change the type to whatever type you use
    Fruit Fruit { get; }
}

class Tree : Detail, IHasFruit {
    ...
}

class Bush : Detail, IHasFruit {
    ...
}

现在,您可以编写一个GetFruit方法:

public Fruit GetFruit(int index) {
    Detail detail = details[index];
    return (detail as IHasFruit)?.Fruit; // this will return null if the detail has no fruit.
}

答案 1 :(得分:0)

您也可以使用IHasFruit接口来获得成果,而您可以通过该接口循环浏览。

IHasFruit [] myArray

或者如果您需要使用

Detail[] myArray
foreach (var item in myArray)
{
     If (item  is IHasFruit hasFruit)
         //do whatever
}

或带有反射(较慢)

Detail[] myArray
foreach (var item in myArray)
{
     var hasFruit= item.GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHasFruit<>));
}

或者如果您不想以任何方式使用界面。您可以使用

İtem.GetType().GetProperty("propertyName") ...