2010-05-14 73 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(); 
} 

}

相關問題