介面只聲明、無實現、不能執行個體化;
介面可包含方法、屬性、事件、索引器, 但無欄位;
介面成員都是隱式的 public, 不要使用存取修飾詞;
類、結構和介面都可以繼承多個介面;
繼承介面的類必須實現介面成員, 除非是抽象類別;
類實現的介面成員須是公用的、非靜態.
入門樣本:
using System;interface MyInterface{ int Sqr(int x);}class MyClass : MyInterface{ public int Sqr(int x) { return x * x; }}class Program{ static void Main() { MyClass obj = new MyClass(); Console.WriteLine(obj.Sqr(3)); // 9 MyInterface intf = new MyClass(); Console.WriteLine(intf.Sqr(3)); Console.ReadKey(); }}
一個介面得到不同的實現:
using System;interface MyInterface{ int Method(int x, int y);}class MyClass1 : MyInterface{ public int Method(int x, int y) { return x + y; }}class MyClass2 : MyInterface{ public int Method(int x, int y) { return x - y; }}class Program{ static void Main() { MyInterface intf1 = new MyClass1(); MyInterface intf2 = new MyClass2(); Console.WriteLine(intf1.Method(3, 2)); // 5 Console.WriteLine(intf2.Method(3, 2)); // 1 Console.ReadKey(); }}
顯示實現介面(介面名.方法):
using System;interface MyInterface1{ void Method();}interface MyInterface2{ void Method();}class MyClass : MyInterface1, MyInterface2{ /* 顯示實現介面不需要存取修飾詞; 但顯示實現的方法只能通過介面訪問 */ void MyInterface1.Method() { Console.WriteLine("MyInterface1_Method"); } void MyInterface2.Method() { Console.WriteLine("MyInterface2_Method"); }}class Program{ static void Main() { MyInterface1 intf1 = new MyClass(); MyInterface2 intf2 = new MyClass(); intf1.Method(); // MyInterface1_Method intf2.Method(); // MyInterface2_Method Console.ReadKey(); }}