C# 多态性

多态性和重写方法

多态性意味着“多种形式”,当我们有许多通过继承相互关联的类时,就会发生多态性。

就像我们在上一章中指定的那样;继承允许我们从另一个类继承字段和方法。多态性使用这些方法来执行不同的任务。这使我们能够以不同的方式执行单个操作。

例如,考虑一个名为 Animal 的基类,它有一个名为 AnimalSound() 的方法。动物的派生类可以是猪、猫、狗、鸟 - 并且它们也有自己的动物声音实现(猪叫声和猫喵叫声等):

实例

class Animal  // 基类 (父类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("动物发出声音");  
  }  
}  
  
class Pig : Animal  // 派生类 (子类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("猪说:wee wee");  
  }  
}  
  
class Dog : Animal  // 派生类 (子类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("狗说:汪汪");  
  }  
}

提示:继承章节中记住,我们使用 : 符号从一个类继承。

现在我们可以创建 PigDog 对象,并在它们两者上调用 animalSound() 方法:

实例

class Animal  // 基类 (父类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("动物发出声音");  
  }  
}  
  
class Pig : Animal  // 派生类 (子类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("猪说:wee wee");  
  }  
}  
  
class Dog : Animal  // 派生类 (子类)   
{  
  public void animalSound()
  {  
    Console.WriteLine("狗说:汪汪");  
  }  
}  
  
class Program   
{  
  static void Main(string[] args)   
  {  
    Animal myAnimal = new Animal();  // 创建一个 Animal 对象  
    Animal myPig = new Pig();  // 创建一个 Pig 对象  
    Animal myDog = new Dog();  // 创建一个 Dog 对象  
  
    myAnimal.animalSound();  
    myPig.animalSound();  
    myDog.animalSound();  
  }  
}

输出将是:

动物发出声音
动物发出声音
动物发出声音

亲自试一试

不是我想要的输出

上面的例子的输出可能不是您所期望的。这是因为当它们共享相同的名称时,基类方法会覆盖派生类方法。

但是,C# 提供了重写基类方法的选项,方法是向基类内部的方法添加 virtual 关键字,并为每个派生类方法使用 override 关键字:

实例

class Animal  // 基类 (父类)   
{  
  public virtual void animalSound()
  {  
    Console.WriteLine("动物发出声音");  
  }  
}  
  
class Pig : Animal  // 派生类 (子类)   
{  
  public override void animalSound()
  {  
    Console.WriteLine("猪说:wee wee");  
  }  
}  
  
class Dog : Animal  // 派生类 (子类)   
{  
  public override void animalSound()
  {  
    Console.WriteLine("狗说:汪汪");  
  }  
}  
  
class Program   
{  
  static void Main(string[] args)   
  {  
    Animal myAnimal = new Animal();  // 创建一个 Animal 对象  
    Animal myPig = new Pig();  // 创建一个 Pig 对象  
    Animal myDog = new Dog();  // 创建一个 Dog 对象  
  
    myAnimal.animalSound();  
    myPig.animalSound();  
    myDog.animalSound();  
  }  
}

输出将是:

动物发出声音
猪说:wee wee
狗说:汪汪

亲自试一试

为什么以及何时使用“继承”和“多态”?

- 它对于代码可重用性很有用:创建新类时重用现有类的字段和方法。