inheritance自具有相同方法签名的多个接口的类

说,我有三个接口:

public interface I1 { void XYZ(); } public interface I2 { void XYZ(); } public interface I3 { void XYZ(); } 

inheritance自这三个接口的类:

 class ABC: I1,I2, I3 { // method definitions } 

问题:

  • 如果我这样实现:

    ABC类:I1,I2,I3 {

      public void XYZ() { MessageBox.Show("WOW"); } 

    }

它编译得很好,也运行得很好! 这是否意味着这个单一方法实现足以inheritance所有三个接口?

  • 如何实现所有三个接口的方法并调用它们 ? 像这样的东西:

     ABC abc = new ABC(); abc.XYZ(); // for I1 ? abc.XYZ(); // for I2 ? abc.XYZ(); // for I3 ? 

我知道它可以使用显式实现完成,但我无法调用它们。 🙁

如果使用显式实现,则必须将对象强制转换为要调用其方法的接口:

 class ABC: I1,I2, I3 { void I1.XYZ() { /* .... */ } void I2.XYZ() { /* .... */ } void I3.XYZ() { /* .... */ } } ABC abc = new ABC(); ((I1) abc).XYZ(); // calls the I1 version ((I2) abc).XYZ(); // calls the I2 version 

你可以打电话给它。 您只需使用具有接口类型的引用:

 I1 abc = new ABC(); abc.XYZ(); 

如果你有:

 ABC abc = new ABC(); 

你可以做:

 I1 abcI1 = abc; abcI1.XYZ(); 

要么:

 ((I1)abc).XYZ(); 

在类中实现期间不指定修饰符o / w您将得到编译错误,还要指定接口名称以避免歧义。您可以尝试代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleCSharp { class Program { static void Main(string[] args) { MyClass mclass = new MyClass(); IA IAClass = (IA) mclass; IB IBClass = (IB)mclass; string test1 = IAClass.Foo(); string test33 = IBClass.Foo(); int inttest = IAClass.Foo2(); string test2 = IBClass.Foo2(); Console.ReadKey(); } } public class MyClass : IA, IB { static MyClass() { Console.WriteLine("Public class having static constructor instantiated."); } string IA.Foo() { Console.WriteLine("IA interface Foo method implemented."); return ""; } string IB.Foo() { Console.WriteLine("IB interface Foo method having different implementation. "); return ""; } int IA.Foo2() { Console.WriteLine("IA-Foo2 which retruns an integer."); return 0; } string IB.Foo2() { Console.WriteLine("IA-Foo2 which retruns an string."); return ""; } } public interface IA { string Foo(); //same return type int Foo2(); //different return tupe } public interface IB { string Foo(); string Foo2(); } 

}