標籤:instance interface des 指南 nbsp bsp sse first mem
介面只包含方法、屬性、事件或索引器的簽名。 實現介面的類或結構必須實現介面定義中指定的介面成員。 在下面的樣本,類 ImplementationClass必須實現一個不具有參數並返回 void 的名為 SampleMethod 的方法。
樣本
1 interface ISampleInterface 2 { 3 void SampleMethod(); 4 } 5 6 class ImplementationClass : ISampleInterface 7 { 8 // Explicit interface member implementation: 9 void ISampleInterface.SampleMethod()10 {11 // Method implementation.12 }13 14 static void Main()15 {16 // Declare an interface instance.17 ISampleInterface obj = new ImplementationClass();18 19 // Call the member.20 obj.SampleMethod();21 }22 }
介面可以是命名空間或類的成員,並且可以包含下列成員的簽名:
一個介面可從一個或多個基底介面繼承。
當基底類型列表包含基類和介面時,基類必須是列表中的第一項。
實現介面的類可以顯式實現該介面的成員。 顯式實現的成員不能通過類執行個體訪問,而只能通過介面執行個體訪問。
樣本
下面的樣本示範了介面實現。 在此樣本中,介面包含屬性聲明,類包含實現。 實現 IPoint 的類的任何執行個體都具有整數屬性 x 和 y。
1 interface IPoint 2 { 3 // Property signatures: 4 int x 5 { 6 get; 7 set; 8 } 9 10 int y11 {12 get;13 set;14 }15 }16 17 class Point : IPoint18 {19 // Fields:20 private int _x;21 private int _y;22 23 // Constructor:24 public Point(int x, int y)25 {26 _x = x;27 _y = y;28 }29 30 // Property implementation:31 public int x32 {33 get34 {35 return _x;36 }37 38 set39 {40 _x = value;41 }42 }43 44 public int y45 {46 get47 {48 return _y;49 }50 set51 {52 _y = value;53 }54 }55 }56 57 class MainClass58 {59 static void PrintPoint(IPoint p)60 {61 Console.WriteLine("x={0}, y={1}", p.x, p.y);62 }63 64 static void Main()65 {66 Point p = new Point(2, 3);67 Console.Write("My Point: ");68 PrintPoint(p);69 }70 }71 // Output: My Point: x=2, y=3
介面(C# 參考)