0

我想执行一些通用代码并初始化许多类共有的变量。在基类中完成所有这些工作是有意义的。然后,根据创建的数据,我想执行一些特定于特定功能的代码。我觉得这些函数应该在从基类派生的类中。但是,我也希望能够访问在基类中初始化的数据。

像这样的东西:

class Animal
{
    public Animal()
    {
        public int _earCount = 2;
        // determine if the planet is all water or all land
    }
}

class Dog : Animal
{
    public WagEars()
    {
    // for each ear, execute code to wag it
    }
}

class Whale : Animal
{
    public FlipTail()
    {
    // code to flip
    }
}

public main()
{
    Animal fred = new Animal;
    // what code goes here to invoke WagEars if the planet is all land?
}

本质上,我要做的是为所有对象执行通用的页眉/页脚类型代码,中间有一些特定于派生类的代码。

创建 fred 时,直到执行公共代码后,我才知道它是狗还是鲸鱼。

4

2 回答 2

0

您可能想要的是以下内容:

public main()
{
    Dog fred = new Dog();
    fred.WagEars();
}

为了调用子类的方法,您需要将变量的类型声明为该类。

或者,您可以执行以下操作:

public main()
{
    Animal fred = new Dog();
    ((Dog)fred).WagEars();
}

如果您将对象向下转换为正确的子类,您将可以访问子类的方法。

于 2012-08-31T17:29:55.243 回答
0

这行得通吗?

if(fred is Dog)
{
  ((Dog)fred).WagEars();
}

if(fred is Whale)
{
  ((Whale)fred).FlipTail();
}
于 2012-08-31T17:54:11.890 回答