新手继承问题

Jim*_*Jim 9 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."); }
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图通过MSDN上c#编程指南,但我发现很难理解那里的一些例子.如果有人可以链接到一个良好的"傻瓜继承"网站,将非常感激.

fle*_*her 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."); }
  }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*off 13

new你写的修饰语:

class Dog : Pets
{
 new public void Say() { Console.WriteLine("Dog barks."); }
}
Run Code Online (Sandbox Code Playgroud)

本质上意味着,Say当该实例使用你定义的方法只调用作为一个实例Dog.

所以

Dog dog = new Dog();
dog.Say(); // barks (calls Dog.Say)
Pet pet = dog;
pet.Say(); // nothing (calls Pet.Say)
Run Code Online (Sandbox Code Playgroud)

这就解释了为什么你收到你的结果 ; 为了你想要的,使用虚拟方法 - @ fletcher的答案解释得很好.