• ASP.Net
  • 常用語法介紹
  • 介面
  • import_contacts Interface介紹
    3701
適用範圍

介面像是一個規範,所以實作的類別都要遵守這個規範,旦不管每一個類別實作的程式碼為何。

實用性:
重要性:

介面可以包含方法、屬性、事件、索引子,或以上四個成員類型的組合

藉由使用介面,在類別中包含多個來源的行為

假設網站有訊息、商品、FAQ…等系統的單元,那頁面上都需要在導覽列顯示目前所在的分類結構,那些系統就得照著interface所定義的規格來實作, 例如訊息只有1層分類,商品有3層分類、FAQ有2層分類,那就照著interface的規範各自實作所需的程式碼。

另外若頁面上需要將Page、MasterPage、UserControl之間互相傳遞資料或呼叫方法、類別…等,也可以使用介面來定義後實作。

使用 interface 關鍵字來定義介面

public interface testSample
{
    void SampleMethod(string str);
}

下列範例示範介面的實作

public class MyPage : testSample
{   
    public void SampleMethod(string str)
    {
        HttpContext.Current.Response.Write(str);
    }
}

實作兩個介面的成員

public interface testSample1
{
    void wrString(string str);
}

public interface testSample2
{
    void wrInt(int value);
}
public class MyPage : testSample1,testSample2
{   
    public void wrString(string str)
    {
        HttpContext.Current.Response.Write(str);
    }

    public void wrInt(int value)
    {
        HttpContext.Current.Response.Write(value.toString());
    }
}