C# 多态
多态和重写方法
多态性意为“多种形式”,它发生在我们有许多通过继承相互关联的类时。
正如我们在上一章中指定的; 继承 允许我们从另一个类继承字段和方法。多态使用这些方法来执行不同的任务。这使我们能够以不同的方式执行单个操作。
例如,考虑一个名为 Animal
的基类,它有一个名为 animalSound()
的方法。动物的派生类可以是猪、猫、狗、鸟 - 它们也有自己对动物声音的实现(猪会发出哼哼声,猫会发出喵喵声等)。
示例
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
还记得我们在 继承章节 中使用 :
符号从类继承吗?
现在我们可以创建 Pig
和 Dog
对象,并在两者上调用 animalSound()
方法。
示例
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
输出将是:
动物发出声音
动物发出声音
动物发出声音
不是我期望的输出
上面示例的输出可能不是您期望的。那是因为当基类方法和派生类方法共享相同名称时,基类方法会覆盖派生类方法。
但是,C# 提供了一个选项来重写基类方法,方法是在基类中的方法中添加 virtual
关键字,并在每个派生类方法中使用 override
关键字。
示例
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
输出将是:
动物发出声音
猪说:哼哼
狗说:汪汪
为什么要使用“继承”和“多态性”?以及何时使用?
- 它有利于代码重用:在创建新类时重用现有类的字段和方法。