2010-05-14 70 views
8

说,我有三个接口:从多个接口继承类具有相同的方法签名

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

类这三个接口继承:

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

问题:

  • 如果我这样实现:

    ABC类:I1,I2,I3 {

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

    }

它编译良好,运行良好呢! 这是否意味着这种单一方法的实现足以继承所有三个接口?

  • 我如何能实现所有三个接口的方法和打电话给他们? 是这样的:

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

我知道它可以使用明确的实施完成,但我不能给他们打电话。 :(

回答

8

如果使用显式实现,那么您必须将对象转换到要调用其方法的接口:

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 
+0

有趣的是,这是可能的C#!就我所知,在Java中不可能单独实现碰撞接口方法。 – 2010-05-14 06:19:09

+1

这是可能的,是的,但我通常不会推荐它(这很令人困惑)。唯一我认为合法的地方就是在执行'ICollection '之类的东西时,你想从普通的类定义中'隐藏'非泛型的'IEnumerable'实现。 – 2010-05-14 06:21:45

2

你可以把它你只需要使用接口类型的引用:

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

如果您有:

ABC abc = new ABC(); 

你可以这样做:

I1 abcI1 = abc; 
abcI1.XYZ(); 

或:

((I1)abc).XYZ(); 
+0

我想调用在ABC的对象...... ABC ABC =新ABC(); ... – Manish 2010-05-14 06:20:49

2

在一个类实现不指定修饰O/W,你会得到编译错误,还指定接口名称,以避免ambiguity.You可以尝试代码:

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(); 
} 

}

相关问题