在C#中实现多态需要使用继承和虚方法。首先,定义一个基类,包含一个或多个虚方法。然后,定义子类,通过继承基类并重写虚方法实现多态。下面是一个简单的示例代码:
public class Shape
{
public virtual double GetArea()
{
return 0;
}
}
public class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public override double GetArea()
{
return Math.PI * radius * radius;
}
}
public class Rectangle: Shape
{
private double width;
private double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public override double GetArea()
{
return width * height;
}
}
在这个示例中,Shape类是基类,包含一个虚方法GetArea(),它返回0。Circle类和Rectangle类是Shape类的子类,它们重写了GetArea()方法,分别返回圆形和矩形的面积。这种实现方式允许使用Shape类的实例来代表Circle类和Rectangle类的实例,并且可以根据具体实例的类型调用相应的方法。
例如:
Shape shape = new Circle(5);
double area = shape.GetArea(); // 返回圆形的面积
shape = new Rectangle(3, 4);
area = shape.GetArea(); // 返回矩形的面积
在这里,我们使用Shape类的实例来代表Circle类和Rectangle类的实例,并且可以调用相应子类的方法,实现了多态。