2 回答

TA貢獻1799條經驗 獲得超8個贊
MakeTree和Bush其他具有Fruit屬性 implement的子類,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.
}

TA貢獻1946條經驗 獲得超4個贊
您也可以為提供水果的類提供 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") ...
- 2 回答
- 0 關注
- 165 瀏覽
添加回答
舉報