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(显式接口实现)
原文:https://www.cnblogs.com/davidshaw/p/10871267.html