interface (C# 參考)

介面只包含方法屬性事件索引的簽章。 類別或結構,其實作的介面必須實作在介面定義中指定的介面成員。 在下列範例中,類別 ImplementationClass 必須實作名為 SampleMethod 的方法,該方法沒有參數並會傳回 void。

如需詳細資訊,請參閱介面 (C# 程式設計手冊)

範例

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

介面可以是命名空間 (Namespace) 或類別的成員,而且可以包含下列成員的簽章:

介面可以繼承一個或多個基底介面。

當基底型別 (Base Type) 清單包含基底類別和介面時,基底類別一定會排在清單的第一個。

實作介面的類別能夠明確實作該介面的成員。 明確實作的成員只能經由該介面的執行個體 (Instance) 來存取,不能經由類別執行個體存取。

如需詳細資訊以及明確介面實作的程式碼範例,請參閱明確介面實作 (C# 程式設計手冊)

下列範例示範了介面實作。 在這個範例中,介面包含屬性宣告,類別則包含實作。 實作 IPoint 之類別的任何執行個體,都有整數屬性 x 和 y。

interface IPoint
{
   // Property signatures:
   int x
   {
      get;
      set;
   }

   int y
   {
      get;
      set;
   }
}

class Point : IPoint
{
   // Fields:
   private int _x;
   private int _y;

   // Constructor:
   public Point(int x, int y)
   {
      _x = x;
      _y = y;
   }

   // Property implementation:
   public int x
   {
      get
      {
         return _x;
      }

      set
      {
         _x = value;
      }
   }

   public int y
   {
      get
      {
         return _y;
      }
      set
      {
         _y = value;
      }
   }
}

class MainClass
{
   static void PrintPoint(IPoint p)
   {
      Console.WriteLine("x={0}, y={1}", p.x, p.y);
   }

   static void Main()
   {
      Point p = new Point(2, 3);
      Console.Write("My Point: ");
      PrintPoint(p);
   }
}
// Output: My Point: x=2, y=3

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

參考型別 (C# 參考)

介面 (C# 程式設計手冊)

使用屬性 (C# 程式設計手冊)

使用索引子 (C# 程式設計手冊)

類別 (C# 參考)

struct (C# 參考)

介面 (C# 程式設計手冊)

概念

C# 程式設計手冊

其他資源

C# 參考