新聞中心
1.公有方法實現C#接口方法

創(chuàng)新互聯建站長期為上1000+客戶提供的網站建設服務,團隊從業(yè)經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態(tài)環(huán)境。為云和企業(yè)提供專業(yè)的成都做網站、成都網站制作,云和網站改版等技術服務。擁有十多年豐富建站經驗和眾多成功案例,為您定制開發(fā)。
盡管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)中的某個公有或私有方法??梢娡ㄟ^接口對方法進行調用需要多出一道轉換工作,因此執(zhí)行效率不如直接調用。
2.私有方法不能實現C#接口方法
如果想將接口方法直接實現為私有方法是辦不到的。下面的EditBox的代碼中Paint方法沒有特殊說明,默認為private,導致代碼無法執(zhí)行:
- 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()“或者是靜態(tài)、非公共的,或者有錯誤的返回類型?!?/p>
由于接口規(guī)范中的方法默認的訪問權限是public,而類中的默認訪問權限是default,也就是說private,因此導致權限范圍收縮,兩者權限并不相同,所以必須將類的權限調整為public才可以使上面的代碼得以執(zhí)行。
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();
- }
- }
當前文章:淺談C#接口方法
本文網址:http://www.5511xx.com/article/dpjpogo.html


咨詢
建站咨詢
