[英]Accessing properties of a child class from list of abstract class objects
我有一個Abstract類Animal,它存儲一些通用字段,例如名稱,健康狀況。 我有許多動物類,例如Tiger,但是我也有Fish類,它有其他動物類沒有的其他字段canSplash
。
然后,我有一個動物對象列表。 我可以訪問公共字段,但是不能訪問Fish的canSplash
字段。 我正在尋找有關從抽象類訪問具體類特定字段的幫助。
class Zoo
{
public List<Animal> animals = new List<Animal>();
public Zoo()
{
animals.Add(new Monkey());
animals.Add(new Tiger());
animals.Add(new Fish());
}
public static void displayZooPopulation()
{
foreach (var a in animals)
{
if (a.species == "fish" && a.CanSplash)
{
Console.WriteLine("{0} can splash",a.Name);
}
}
}
}
class Fish : Animal {
private bool canSplash
public bool CanSplash { get; set; }
}
簡單的答案是,通過安全地強制轉換為類型來檢查類型,並檢查它是否不為null
:
var fish = a as Fish;
if (fish != null && fish.CanSplash)
{
Console.WriteLine("{0} can splash",a.Name);
}
如果您只有一個具有此特定行為的子類,則完全可以。 但是,請考慮您還有其他能夠飛濺的動物子類,比如說一頭大象,那么,如果您想在動物園中找到所有可能飛濺的動物,則還必須檢查大象的類。
更好的方法是將接口用於ISplashable
類的事情:
public interface ISplashable
{
bool CanSplash { get; }
}
現在,在您應該能夠使用的所有子類中實現此接口:
public class Fish : Animal, ISplashable
{
// ...
public bool CanSplash { get; set; } // this also implements CanSplash { get; }
// ...
}
public class Elephant : Animal, ISplashable
{
// ...
public bool CanSplash { get { return true; } }
// ...
}
現在,您可以對照該接口而不是具體的類進行檢查:
var splasher = a as ISplashable;
if (splasher != null && splasher.CanSplash)
{
Console.WriteLine("{0} can splash",a.Name);
}
//刪除static關鍵字,因為您無法訪問動物(或動物應該是靜態的)
檢查的類型,然后采取措施
該方法可以是:
public void displayZooPopulation()
{
foreach (var a in animals)
{
if ( a is Fish)
{
//here sure "a" is not null, no need to check against null
var fish = a as Fish;
// if (a.species == "fish" && (Fish) a.CanSplash)
if ( fish.CanSplash)
{
Console.WriteLine("{0} can splash", a.Name);
}
}
}
}
順便說一句,你說Animal是抽象類,在Fish類中抽象方法的實現在哪里:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.