C#学习之接口
时间: 2023-08-02 13:21:02 浏览: 72
接口是C#中的一种特殊类型,它定义了一组方法和属性,但没有具体的实现。接口通常用于定义类之间的契约,强制实现接口的类必须提供接口中定义的所有方法和属性的实现。以下是使用接口的示例代码:
```csharp
public interface IShape
{
double GetArea();
double GetPerimeter();
}
public class Circle : IShape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public double GetArea()
{
return Math.PI * radius * radius;
}
public double GetPerimeter()
{
return 2 * Math.PI * radius;
}
}
public class Rectangle : IShape
{
private double length;
private double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public double GetArea()
{
return length * width;
}
public double GetPerimeter()
{
return 2 * (length + width);
}
}
```
在这个例子中,`IShape`接口定义了`GetArea`和`GetPerimeter`两个方法,`Circle`和`Rectangle`类分别实现了这个接口,并提供了自己的实现方式。这样,我们就可以通过一个接口来访问不同的实现类,而不需要关心它们具体的实现细节。