C# 访问抽象对象上的具体属性?
我想这是一个基本问题,但如果我想让一个对象拥有另一个类型为a或B的对象,那么使用该对象的应用程序如何访问特定属性呢?例如C# 访问抽象对象上的具体属性?,c#,inheritance,abstract-class,derived-class,C#,Inheritance,Abstract Class,Derived Class,我想这是一个基本问题,但如果我想让一个对象拥有另一个类型为a或B的对象,那么使用该对象的应用程序如何访问特定属性呢?例如 public abstract class Animal { private int Age; // Get Set } public class Tiger: Animal { private int NoStripes; // Get Set } public class Lion : Animal { private
public abstract class Animal
{
private int Age;
// Get Set
}
public class Tiger: Animal
{
private int NoStripes;
// Get Set
}
public class Lion : Animal
{
private bool HasMane;
// Get Set
}
public class Zoo
{
private Animal animal;
// Get Set
}
public static void Main()
{
Zoo zoo = new Zoo();
zoo.animal = new Tiger();
// want to set Tiger.NoStripes
}
您必须将
zoo.Animal
投给Tiger
或者你可以试试类似的东西
public abstract class Animal
{
public int Age;
// Get Set
}
public class Tiger : Animal
{
public int NoStripes;
// Get Set
}
public class Lion : Animal
{
public bool HasMane;
// Get Set
}
public class Zoo<T> where T : Animal
{
public T animal;
// Get Set
}
Zoo<Tiger> zoo = new Zoo<Tiger>();
zoo.animal = new Tiger();
zoo.animal.NoStripes = 1;
公共抽象类动物
{
公共信息;
//准备好
}
公营老虎:动物
{
公众意见;
//准备好
}
公营狮子:动物
{
公共图书馆;
//准备好
}
公营动物园T:动物
{
公畜;
//准备好
}
动物园=新动物园();
zoo.animal=新老虎();
zoo.animal.NoStripes=1;
直接的答案是
public static void Main() {
Zoo zoo = new Zoo();
zoo.animal = new Tiger();
((Tiger)zoo.Animal).NoStripes = 10;
}
当然,要让它起作用,你需要知道zoo.Animal
实际上是一只老虎。您可以使用zoo.animalistiger
进行测试(尽管as
操作符比is
更可取)
然而,一般来说,像这样设计程序并不是很好。您必须编写的代码可能会很麻烦。这是继承和多态性的要点
如果您能够确定动物的实例实际上是老虎的实例,则可以将其施放:
((Tiger)zoo.Animal).NoStripes = 1;
然而,如果您尝试在不是老虎的动物实例上执行此操作,您将得到一个运行时异常
例如:
Zoo zoo = new Zoo();
zoo.animal = new Tiger();
((Tiger)zoo.Animal).NoStripes = 1; //Works Fine
((Lion)zoo.Animal).NoStripes = 1; //!Boom - The compiler allows this, but at runtime it will fail.
还有一种替代的强制转换语法,即使用“as”关键字,如果强制转换失败,它将返回null,而不是异常。这听起来不错,但在实践中,当空对象被使用时,您可能会在稍后遇到一些微妙的错误
Tiger temp = zoo.Animal as Tiger; //This will not throw an exception
temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug
zoo.Animal = temp;
为了避免空引用异常,当然可以进行空检查
Tiger temp = zoo.Animal as Tiger; //This will not throw an exception
if (temp != null)
{
temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug
zoo.Animal = temp;
}
同意了,那怎么解决呢?如果您有一个包含或的对象,例如车库有a车或B车,那么这方面的最佳设计实践是什么?在包含对象中同时创建A和B似乎也是错误的。。。