C# 接口(Interface)
C# 接口(Interface)
接口定義了所有類繼承接口時應遵循的語法合同。接口定義了語法合同 "是什么" 部分,派生類定義了語法合同 "怎么做" 部分。
接口定義了屬性、方法和事件,這些都是接口的成員。接口只包含了成員的聲明。成員的定義是派生類的責任。接口提供了派生類應遵循的標准結構。
接口使得實現接口的類或結構在形式上保持一致。
抽象類在某種程度上與接口類似,但是,它們大多只是用在當只有少數方法由基類聲明由派生類實現時。
定義接口: MyInterface.cs
接口使用 interface 關鍵字聲明,它與類的聲明類似。接口聲明默認是 public 的。下面是一個接口聲明的實例:
interface IMyInterface { void MethodToImplement(); }
以上代碼定義了接口 IMyInterface。通常接口命令以 I 字母開頭,這個接口只有一個方法 MethodToImplement(),沒有參數和返回值,當然我們可以按照需求設置參數和返回值。
值得注意的是,該方法併沒有具體的實現。
接下來我們來實現以上接口:InterfaceImplementer.cs
using System; interface IMyInterface { // 接口成員 void MethodToImplement(); } class InterfaceImplementer : IMyInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } }
InterfaceImplementer 類實現了 IMyInterface 接口,接口的實現與類的繼承語法格式類似:
class InterfaceImplementer : IMyInterface
繼承接口後,我們需要實現接口的方法 MethodToImplement() , 方法名必須與接口定義的方法名一致。
接口繼承: InterfaceInheritance.cs
以下實例定義了兩個接口 IMyInterface 和 IParentInterface。
如果一個接口繼承其他接口,那么實現類或結構就需要實現所有接口的成員。
以下實例 IMyInterface 繼承了 IParentInterface 接口,因此接口實現類必須實現 MethodToImplement() 和 ParentInterfaceMethod() 方法:
using System; interface IParentInterface { void ParentInterfaceMethod(); } interface IMyInterface : IParentInterface { void MethodToImplement(); } class InterfaceImplementer : IMyInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); iImp.ParentInterfaceMethod(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } public void ParentInterfaceMethod() { Console.WriteLine("ParentInterfaceMethod() called."); } }
實例輸出結果為:
MethodToImplement() called. ParentInterfaceMethod() called.