溫馨提示×

C#中怎么實現多態性

c#
小億
116
2024-03-06 17:29:53
欄目: 編程語言

在C#中實現多態性一般通過繼承和接口實現。具體方法如下:

  1. 繼承:通過創建一個父類和多個子類,子類繼承父類的特性,并且可以重寫父類的方法來實現多態性。例如:
class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

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

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

Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.MakeSound(); // Output: Dog barks
myCat.MakeSound(); // Output: Cat meows
  1. 接口:通過定義一個接口,然后讓多個類實現這個接口,實現接口方法的多態性。例如:
interface IShape
{
    double GetArea();
}

class Circle : IShape
{
    public double Radius { get; set; }

    public double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}

class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double GetArea()
    {
        return Width * Height;
    }
}

IShape myCircle = new Circle() { Radius = 5 };
IShape myRectangle = new Rectangle() { Width = 5, Height = 10 };

Console.WriteLine(myCircle.GetArea()); // Output: 78.54
Console.WriteLine(myRectangle.GetArea()); // Output: 50

通過以上兩種方法,可以實現不同類對象對同一個方法的調用,實現多態性。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女