我會感謝您對以下建議:優雅的動態類型鑄造
我使用多態性。我有一個基類和30個繼承這個基類的子類。我將這些子類的實例轉換爲基類類型,以便能夠以更通用的方式處理它們。
我的問題是這樣的。 我需要訪問特定於特定子類的公共屬性。我是否需要編寫一個巨大的病例聲明來檢查類型並進行相應的轉換以便訪問我需要的屬性或者是否有更優雅的解決方案?
static void Main(string[] args)
{
animal slyvester = new cat();
animal lassie = new dog();
animal silver = new horse();
// Big ugly type checking code. If I have 30 types to check is there a better way?
if (slyvester.GetType() == typeof(cat)) {
Console.WriteLine(((cat)(animal)slyvester).PurrStrength);
}
else if(slyvester.GetType() == typeof(dog)) {
}
else if (slyvester.GetType() == typeof(horse))
{
}
Console.ReadLine();
}
}
public class animal {
}
public class cat : animal {
private string _purrStrength = "Teeth Shattering";
public string PurrStrength {
get { return _purrStrength; }
set { _purrStrength = value; }
}
}
public class dog : animal {
}
public class horse : animal {
}
現在的問題是:你確定在查詢哪一種類型的時刻? – Tigran
每個動物都有特定的屬性,你想閱讀,或只是貓?換句話說,else if(slyvester.GetType()== typeof(dog))''會發生什麼? –
真正的問題是,你想要做什麼? –