C Sharp/Interfaces

維基教科書,自由的教學讀本

接口是C#的一種類型,是對象和使用者之間的約定(contract)。它只包含方法和屬性的聲明,不能有數據成員和任何實現。如:

interface IShape
{
    double X { get; set; }
    double Y { get; set; }
    void Draw();
}

.NET Framework通常用大寫字母"I"作為接口名字的第一個字符。如果接口只定義了一個主要方法(如上例),則可用"...able"作為接口名字的後綴。如上例可命名為IDrawable.

實現接口的類需要繼承它,並實現所有的方法和屬性。如:

class Square : IShape
{
    private double _mX, _mY;

    public void Draw() { ... }

    public double X 
    { 
        set { _mX = value; }
        get { return _mX; }  
    }

    public double Y 
    {
        set { _mY = value; }
        get { return _mY; }
    }
}

類可以同時繼承多個接口:

class MyClass : Class1, Interface1, Interface2 { ... }

對象可以用接口作為其引用:

class MyClass 
{
    static void Main()
    {
        IShape shape = new Square();
        shape.Draw();
    }
}

接口可以繼承其他接口,但不能從類繼承:

interface IRotateable
{
    void Rotate(double theta);
}

interface IDrawable : IRotateable
{
    void Draw();
}

額外細節[編輯]

接口的成員都是public。

實現類可以把接口的方法定義為虛方法。

接口沒有靜態方法。

接口可以聲明事件和索引器(indexer)。

For those familiar with Java, C#'s interfaces are extremely similar to Java's.