1. 程式人生 > >C# explicit interface implementation(顯式接口實現)

C# explicit interface implementation(顯式接口實現)

cit print tel xpl color exp static 調用 inf

C# explixit interface implementation

某個類要實現兩個包含相同方法名的接口, 應該如何實現這兩個方法?

技術分享圖片

 1 namespace ExplicitInterfaceImplementation
 2 {
 3     class Program : IPrintOne,IPrintTwo, IPrintThree
 4     {
 5         static void Main(string[] args)
 6         {
 7             Program p = new Program();
 8             p.Print();
9 (p as IPrintTwo).Print(); 10 ((IPrintThree)p).Print(); 11 } 12 13 14 15 public void Print() 16 { 17 Console.WriteLine("Print One Interface"); 18 } 19 // explicitly implement IPrintTwo 20 void IPrintTwo.Print()
21 { 22 Console.WriteLine("Print Two Interface"); 23 } 24 // explicitly implement IPrintThree 25 string IPrintThree.Print() 26 { 27 Console.WriteLine("Print two Interface"); 28 return "asd"; 29 } 30 } 31 32
interface IPrintOne 33 { 34 void Print(); 35 } 36 37 interface IPrintTwo 38 { 39 void Print(); 40 } 41 42 interface IPrintThree 43 { 44 string Print(); 45 } 46 }

以上Demo中共有3個擁有相同方法名的interface,Program類繼承了這三個接口,使用explicit interface implementation實現IPrintTwo和IPrintThree接口的方法

顯示實現的接口方法前不能加access modifier,且調用該方法時需將Program類轉換位接口才能調用, 不能直接通過類引用調用。

When a class explicitly implements an interface member, the interface member can no longer be accessed thru class reference variable, but only thru the interface reference variable.

以上Demo的運行結果:

Print One Interface  
Print Two Interface  
Print Three Interface  

C# explicit interface implementation(顯式接口實現)