一小段代码演示C#接口的类级别实现和显式接口成员实现

来源:互联网 发布:大数据技术与应用就业 编辑:程序博客网 时间:2024/05/24 06:00

拿《C#图解教程》书中代码做的试验:

using System;namespace Examples{   interface IIfc1 { void PrintOut( string s ); }    interface IIfc2 { void PrintOut( string t ); }    class MyClass : IIfc1, IIfc2   {      void IIfc1.PrintOut( string s ) // 显式接口成员实现      {         Console.WriteLine( "IIfc1: {0}", s );      }      void IIfc2.PrintOut( string s ) // 显式接口成员实现      {         Console.WriteLine( "IIfc2: {0}", s );      }      public void PrintOut(string s) // 类级别实现      {          Console.WriteLine("MyClass: {0}", s);      }   }   class Program   {      static void Main()      {         MyClass mc = new MyClass();         mc.PrintOut( "Hello" );         IIfc1 ifc1 = (IIfc1) mc;           ifc1.PrintOut( "Hello" );           IIfc2 ifc2 = (IIfc2) mc;           ifc2.PrintOut( "Hello" );       }// 设置断点   }}/*输出:MyClass: HelloIIfc1: HelloIIfc2: Hello*/


如果 只有 显式接口成员的实现,没有 类级别的实现,那么  不能直接用MyClass的引用访问实现,只能强制转换为接口的引用才能访问实现。例如:

using System;namespace Examples{   interface IIfc1 { void PrintOut( string s ); }    interface IIfc2 { void PrintOut( string t ); }    class MyClass : IIfc1, IIfc2   {      void IIfc1.PrintOut( string s )       { // implementation         Console.WriteLine( "IIfc1: {0}", s );      }      void IIfc2.PrintOut( string s )       { // implementation         Console.WriteLine( "IIfc2: {0}", s );      }      public void Method1( string s )      {          // this.PrintOut(s); It does not exist!          ((IIfc1) this).PrintOut(s);      }   }   class Program   {      static void Main()      {         MyClass mc = new MyClass();          IIfc1 ifc1 = (IIfc1) mc;         ifc1.PrintOut( "Hello" );         IIfc2 ifc2 = (IIfc2) mc;          ifc2.PrintOut( "Hello" );         mc.Method1( "Hello" );      }// 设置断点   }}/*输出:IIfc1: HelloIIfc2: HelloIIfc1: Hello*/


0 0