C#顯式實(shí)現(xiàn)接口原理淺析
C#顯式實(shí)現(xiàn)接口方法是什么情況呢?當(dāng)一個(gè)類(lèi)實(shí)現(xiàn)了兩個(gè)接口(假設(shè)Document 類(lèi)實(shí)現(xiàn)了IStorable和ITalk接口),但是兩個(gè)接口中有方法名相同時(shí),可以使用下面的語(yǔ)法來(lái)顯式地實(shí)現(xiàn)一個(gè)接口:
- void ITalk.Read()
 
C#顯式實(shí)現(xiàn)接口的方法時(shí),不可以加訪問(wèn)修飾符(access modifier),將隱式地聲明為public。
不能通過(guò)類(lèi)的實(shí)例來(lái)直接訪問(wèn)顯式實(shí)現(xiàn)的方法。假設(shè)該類(lèi)還實(shí)現(xiàn)了IStorable接口中的Read()的方法,當(dāng)使用下面的語(yǔ)句時(shí):
- theDoc.Read( );
 
將會(huì)隱式調(diào)用IStorable的Read() 方法。
如果該類(lèi)僅實(shí)現(xiàn)了ITalk接口,而沒(méi)有實(shí)現(xiàn)IStorable接口,也就不存在方法名沖突的情況,但是卻仍使用顯示的接口聲明,那么當(dāng)使用 theDoc.Read() 時(shí),將會(huì)出現(xiàn)編譯錯(cuò)誤。
- 'ExplicitImplementation.Document
 - ' does not contain a definition for
 - 'Read' F:\MyApp\Test\ExplictImplament.cs 57 11 Test
 
當(dāng)想使用 ITalk接口的方法時(shí),需要進(jìn)行一次類(lèi)型轉(zhuǎn)換,使用下面的語(yǔ)法:
- ITalk itDoc = theDoc;
 - itDoc.Read();
 
C#顯式實(shí)現(xiàn)接口之成員隱藏
假設(shè)有如下兩個(gè)接口:
- interface IBase
 - {
 - int P { get; set; }
 - }
 - interface IDerived : IBase
 - {
 - new int P();
 - }
 
繼承 IDerived的類(lèi)至少需要進(jìn)行一個(gè)顯示實(shí)現(xiàn)。
- class myClass : IDerived
 - it55.com
 - {
 - int IBase.P { get {...} }
 - public int P( ) {...}
 - }
 - class myClass : IDerived
 - {
 - public int P { get {...} }
 - int IDerived.P( ) {...}
 - }
 - class myClass : IDerived
 - {
 - int IBase.P { get {...} }
 - int IDerived.P( ) {...}
 - }
 
C#顯式實(shí)現(xiàn)接口之實(shí)現(xiàn)接口的值類(lèi)型(Struct)
如果使用值類(lèi)型實(shí)現(xiàn)接口,則應(yīng)通過(guò)值類(lèi)型的對(duì)象訪問(wèn)接口方法,而不要轉(zhuǎn)換成接口,再用接口進(jìn)行訪問(wèn),此時(shí)會(huì)多出一個(gè)“復(fù)制”了的引用對(duì)象,而原來(lái)的值對(duì)象依然存在,兩個(gè)對(duì)象是各自獨(dú)立的。
- myStruct theStruct = new myStruct( );
 - theStruct.Status = 2;
 - IStorable isTemp = ( IStorable ) theStruct;
 - it55.com
 - Console.WriteLine( "isTemp: {0}", isTemp.Status );
 - isTemp.Status = 4;
 - Console.WriteLine("theStruct:{0},
 - isTemp: {1}",theStruct.Status, isTemp.Status );
 - theStruct.Status = 6;
 - Console.WriteLine( "theStruct: {0},
 - isTemp: {1}",theStruct.Status, isTemp.Status );
 
C#顯式實(shí)現(xiàn)接口之程序輸出:
- isTemp: 2
 - theStruct: 2, isTemp: 4
 - theStruct: 6, isTemp: 4
 
C#顯式實(shí)現(xiàn)接口的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#顯式實(shí)現(xiàn)接口有所幫助。
【編輯推薦】















 
 
 
 
 
 
 