我会感谢您对以下建议:优雅的动态类型铸造
我使用多态性。我有一个基类和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))''会发生什么? –
真正的问题是,你想要做什么? –