C#为什么我们使用界面

示例

接口是接口用户与实现接口的类之间的契约的定义。想到接口的一种方法是声明对象可以执行某些功能。

假设我们定义了一个接口IShape来表示不同类型的形状,我们希望一个形状具有一个面积,因此我们将定义一个方法来强制接口实现返回其面积:

public interface IShape
{
    double ComputeArea();
}

我们有以下两种形状:aRectangle和aCircle

public class Rectangle : IShape
{
    private double length;
    private double width;

    public Rectangle(double length, double width)
    {
       this.length= length;
       this.width= width;
    }

    public double ComputeArea()
    {
        return length * width;
    }
}

public class Circle : IShape
{
    private double radius;

    public Circle(double radius)
    {
       this.radius= radius;
    }

    public double ComputeArea()
    {
        return Math.Pow(radius, 2.0) * Math.PI;
    }
}

它们每个都有自己的区域定义,但它们都是形状。因此,IShape在我们的程序中看到它们是合乎逻辑的:

private static void Main(string[] args)
{
    var shapes = new List<IShape>() { new Rectangle(5, 10), new Circle(5) };
    ComputeArea(shapes);

    Console.ReadKey();
}

private static void ComputeArea(IEnumerable<IShape> shapes) 
{
    foreach (shape in shapes)
    {
        Console.WriteLine("Area: {0:N}, shape.ComputeArea());
    }
}

// 输出:
// 面积:50.00
// 面积:78.54