温馨提示×

C#中怎么实现多态性

c#
小亿
90
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