C# explicit interface implementation 某個類要實現兩個包含相同方法名的介面, 應該如何實現這兩個方法? 以上Demo中共有3個擁有相同方法名的interface,Program類繼承了這三個介面,使用explicit interface implementatio ...
C# explicit 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