淺談C#接口方法
1.公有方法實現C#接口方法
盡管C#在定義接口時不用指明接口方法的訪問控制方式,但默認接口方法均為public型(這可以從反編譯的IL代碼中看到)。下面是使用Reflector查看的接口IL代碼:
- class private interface abstract auto ansi IControl{
- method public hidebysig newslot abstract virtual instance void Paint() cil managed{
- }
- }
實現接口的類需要實現所有接口方法。通常情況下,接口的實現方法也為public型。如下案例:
- using System ;
- interface IControl
- {
- void Paint();
- }
- public class EditBox: IControl
- {
- public void Paint()
- {
- Console.WriteLine("Pain method is called!");
- }
- }
- class Test
- {
- static void Main()
- {
- EditBox editbox = new EditBox();
- editbox.Paint();
- ((IControl)editbox)。Paint();
- }
- }
接口就好像是關系型數據庫中的一對多表,一個接口對應多個接口方法,每個接口方法又對應虛擬方法表(VMT)中的某個公有或私有方法。可見通過接口對方法進行調用需要多出一道轉換工作,因此執行效率不如直接調用。
2.私有方法不能實現C#接口方法
如果想將接口方法直接實現為私有方法是辦不到的。下面的EditBox的代碼中Paint方法沒有特殊說明,默認為private,導致代碼無法執行:
- using System ;
- interface IControl
- {
- void Paint();
- }
- public class EditBox: IControl
- {
- void Paint()
- {
- Console.WriteLine("Pain method is called!");
- }
- public void ShowPaint()
- {
- this.Paint();
- ((IControl)this)。Paint();
- }
- }
- class Test
- {
- static void Main()
- {
- EditBox editbox = new EditBox();
- editbox.ShowPaint();
- }
- }
程序在編譯時將顯示如下編譯錯誤:“”EditBox“不會實現接口成員”IControl.Paint()“。”EditBox.Paint()“或者是靜態、非公共的,或者有錯誤的返回類型?!?/P>
由于接口規范中的方法默認的訪問權限是public,而類中的默認訪問權限是default,也就是說private,因此導致權限范圍收縮,兩者權限并不相同,所以必須將類的權限調整為public才可以使上面的代碼得以執行。
3.實現專門的C#接口方法
- using System ;
- interface IControl
- {
- void Paint();
- }
- public class EditBox: IControl
- {
- void Paint()
- {
- Console.WriteLine("Pain method is called!");
- }
- void IControl.Paint()
- {
- Console.WriteLine("IControl.Pain method is called!");
- }
- public void ShowPaint()
- {
- this.Paint();
- ((IControl)this)。Paint();
- }
- }
- class Test
- {
- static void Main()
- {
- EditBox editbox = new EditBox();
- editbox.ShowPaint();
- //editbox.Paint();
- ((IControl)editbox)。Paint();
- }
- }
【編輯推薦】