C#顯式實(shí)現(xiàn)接口原理淺析
C#顯式實(shí)現(xiàn)接口方法是什么情況呢?當(dāng)一個(gè)類實(shí)現(xiàn)了兩個(gè)接口(假設(shè)Document 類實(shí)現(xiàn)了IStorable和ITalk接口),但是兩個(gè)接口中有方法名相同時(shí),可以使用下面的語法來顯式地實(shí)現(xiàn)一個(gè)接口:
- void ITalk.Read()
 
C#顯式實(shí)現(xiàn)接口的方法時(shí),不可以加訪問修飾符(access modifier),將隱式地聲明為public。
不能通過類的實(shí)例來直接訪問顯式實(shí)現(xiàn)的方法。假設(shè)該類還實(shí)現(xiàn)了IStorable接口中的Read()的方法,當(dāng)使用下面的語句時(shí):
- theDoc.Read( );
 
將會隱式調(diào)用IStorable的Read() 方法。
如果該類僅實(shí)現(xiàn)了ITalk接口,而沒有實(shí)現(xiàn)IStorable接口,也就不存在方法名沖突的情況,但是卻仍使用顯示的接口聲明,那么當(dāng)使用 theDoc.Read() 時(shí),將會出現(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)行一次類型轉(zhuǎn)換,使用下面的語法:
- ITalk itDoc = theDoc;
 - itDoc.Read();
 
C#顯式實(shí)現(xiàn)接口之成員隱藏
假設(shè)有如下兩個(gè)接口:
- interface IBase
 - {
 - int P { get; set; }
 - }
 - interface IDerived : IBase
 - {
 - new int P();
 - }
 
繼承 IDerived的類至少需要進(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)接口的值類型(Struct)
如果使用值類型實(shí)現(xiàn)接口,則應(yīng)通過值類型的對象訪問接口方法,而不要轉(zhuǎn)換成接口,再用接口進(jìn)行訪問,此時(shí)會多出一個(gè)“復(fù)制”了的引用對象,而原來的值對象依然存在,兩個(gè)對象是各自獨(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)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C#顯式實(shí)現(xiàn)接口有所幫助。
【編輯推薦】















 
 
 
 
 
 
 