1

我猜是一个基本问题,但是如果我希望一个对象拥有另一个类型为 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 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
}
4

3 回答 3

2

你将不得不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;
于 2010-12-22T12:03:24.857 回答
0

直接的答案是做

public static void Main() {
    Zoo zoo = new Zoo();
    zoo.animal = new Tiger();

    ((Tiger)zoo.Animal).NoStripes = 10;
}

当然,要让它工作,你需要知道它zoo.Animal实际上是一个Tiger. 您可以使用它zoo.Animal is Tiger来测试(尽管as运算符比 . 更可取is)。

然而,一般来说,像这样设计你的程序并不好闻。您必须编写的代码可能会很麻烦。

于 2010-12-22T12:03:50.823 回答
0

这是继承和多态的要点。

如果您能够确定 Animal 的实例实际上是 Tiger 的实例,则可以强制转换它:

((Tiger)zoo.Animal).NoStripes = 1;

但是,如果您尝试在不是 Tiger 的 Animal 实例上执行此操作,您将获得运行时异常。

例如:

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;
}
于 2010-12-22T12:04:13.507 回答