另一个多态性的例子

多态性是 OOP 的支柱之一。Poly 来自希腊语,意思是多种形式。

下面是展示多态性的例子。类 Vehicle 将多种形式作为基类。

派生类 Ducati 和 Lamborghini 继承自 Vehicle 并覆盖基类的 Display() 方法,以显示自己的 NumberOfWheels。

public class Vehicle
{
    protected int NumberOfWheels { get; set; } = 0;
    public Vehicle()
    {
    }

    public virtual void Display()
    {
        Console.WriteLine($"The number of wheels for the {nameof(Vehicle)} is {NumberOfWheels}");
    }
}

public class Ducati : Vehicle
{
    public Ducati()
    {
        NoOfWheels = 2;
    }

    public override void Display()
    {
        Console.WriteLine($"The number of wheels for the {nameof(Ducati)} is {NumberOfWheels}");
    }
}

public class Lamborghini : Vehicle
{
    public Lamborghini()
    {
        NoOfWheels = 4;
    }

    public override void Display()
    {
        Console.WriteLine($"The number of wheels for the {nameof(Lamborghini)} is {NumberOfWheels}");
    }
}

下面是展示多态性的代码片段。使用第 1 行的变量 vehicle 为基本类型 Vehicle 创建对象。它在第 2 行调用基类方法 Display() 并显示输出,如图所示。

 static void Main(string[] args)
 {
    Vehicle vehicle = new Vehicle();    //Line 1
    vehicle.Display();                  //Line 2  
    vehicle = new Ducati();             //Line 3
    vehicle.Display();                  //Line 4
    vehicle = new Lamborghini();        //Line 5
    vehicle.Display();                  //Line 6
 }

在第 3 行,vehicle 对象指向派生类 Ducati 并调用其 Display() 方法,该方法显示输出,如图所示。这里有多态行为,即使对象 vehicle 是 Vehicle 类型,它也会调用派生类方法 Display() 作为类型 Ducati 覆盖基类 Display() 方法,因为 vehicle 对象指向 Ducati。

当它调用 Lamborghini 类型的 Display() 方法时,同样的解释是适用的。

输出如下所示

The number of wheels for the Vehicle is 0        // Line 2 
The number of wheels for the Ducati is 2         // Line 4
The number of wheels for the Lamborghini is 4    // Line 6