新手继承问题

时间:2010-08-16 16:53:56

标签: c# inheritance

我不明白为什么我的输出不是我认为应该如何。我认为它应该是Dog barks line break Cat meows。但那里什么都没有。

代码:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public void Say() { }
  }

  class Dog : Pets
  {
   new public void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
   new public void Say() { Console.WriteLine("Cat meows."); }
  }
}

我试图通过c# programming guide on MSDN,但我发现很难理解那里的一些例子。如果有人可以链接到一个好的“傻瓜遗产”网站,那将非常感激。

2 个答案:

答案 0 :(得分:18)

在基类中创建Say函数virtual,然后在派生类中重写此函数:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public virtual void Say() {
      Console.WriteLine("Pet makes generic noise");
 }
  }

  class Dog : Pets
  {
    public override void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
    public override void Say() { Console.WriteLine("Cat meows."); }
  }
}

答案 1 :(得分:13)

您编写的new修饰符:

class Dog : Pets
{
 new public void Say() { Console.WriteLine("Dog barks."); }
}

本质上意味着只有当该实例用作作为Say 的实例时,才会调用您定义的Dog方法。

所以

Dog dog = new Dog();
dog.Say(); // barks (calls Dog.Say)
Pet pet = dog;
pet.Say(); // nothing (calls Pet.Say)

这就解释了为什么你收到了拥有的结果;对于你想要的东西,使用虚拟方法 - @fletcher's answer explains it well

相关问题