在 C# 中,多态(Polymorphism)是面向对象编程的基本特性之一,它允许使用不同的对象和方法来执行同一操作。C# 中实现多态的方式主要是通过虚方法和抽象类。
虚方法是一种允许子类覆盖的方法,它的实现是在运行时动态确定的。C# 中,可以通过在方法前面加上 virtual
关键字来定义一个虚方法。子类可以使用 override
关键字来覆盖基类的虚方法,从而实现多态。下面是一个简单的例子:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound.");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog barks.");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat meows.");
}
}
class Program
{
static void Main(string[] args)
{
Animal animal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();
animal.MakeSound();
dog.MakeSound();
cat.MakeSound();
}
}
输出结果为:
The animal makes a sound.
The dog barks.
The cat meows.
在这个例子中,Animal 类定义了一个虚方法 MakeSound()
,而 Dog 和 Cat 类则分别覆盖了该方法。在 Main 函数中,我们创建了一个 Animal 对象和两个子类对象,并分别调用了它们的 MakeSound()
方法。由于 Dog 和 Cat 类覆盖了 MakeSound()
方法,所以它们的输出结果与基类的不同。
除了虚方法,抽象类也是实现多态的一种方式。抽象类是一种不能被实例化的类,它只能被用作其他类的基类。C# 中,可以通过在方法前面加上 abstract
关键字来定义一个抽象方法。子类必须实现抽象方法,否则子类也必须定义为抽象类。下面是一个简单的例子:
public abstract class Shape
{
public abstract double GetArea();
}
public class Square : Shape
{
private double side;
public Square(double s)
{
side = s;
}
public override double GetArea()
{
return side * side;
}
}
public class Circle : Shape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public override double GetArea()
{
return Math.PI * radius * radius;
}
}
class Program
{
static void Main(string[] args)
{
Shape[] shapes = new Shape[2];
shapes[0] = new Square(5);
shapes[1] = new Circle(3);
foreach (Shape shape in shapes)
{
Console.WriteLine("Area of {0}: {1}", shape.GetType().Name, shape.GetArea());
}
}
}
输出结果为:
Area of Square: 25
Area of Circle: 28.274333882308
当基类中声明的方法被子类重写时,子类的方法将被调用。这种方法调用的行为称为虚方法调用。虚方法调用通过运行时检查确定要调用的方法,这就是多态。
要实现多态和虚方法,需要遵循以下步骤:
- 在基类中声明虚方法:在基类中声明一个方法,并使用
virtual
关键字表示该方法是可重写的。例如:public class Animal { public virtual void MakeSound() { Console.WriteLine("The animal makes a sound"); } }
- 在子类中重写虚方法:在子类中使用
override
关键字重写基类中声明的虚方法。例如:public class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks"); } }
- 创建对象并调用方法:创建一个子类的对象,并调用重写的虚方法。例如:
Animal animal = new Dog(); animal.MakeSound(); // 输出 "The dog barks"
在这个例子中,我们创建了一个
Dog
类的对象,并将其赋值给了一个Animal
类型的变量。然后调用MakeSound()
方法,输出 "The dog barks"。因为MakeSound()
方法被声明为虚方法并且在子类中重写了,所以在运行时会调用子类中的方法,而不是基类中的方法。这就是在 C# 中实现多态和使用虚方法的基本方法。