2011-05-17 69 views

回答

7

如果這就是客戶端代碼使用該類的方式,那並不重要。如果它需要做一些特定於接口的事情,它應該聲明它所需要的接口,並將該類分配給該接口。

I1 i = new TheClass() 
i.TheMethod(); 

當然,使用當前的實現TheClass,這並不重要,如果聲明iI1,或I2,因爲你只需要一個單一的實現。

如果你想每個接口都有一個單獨的實現,那麼你需要創建明確的實現......

void I1.TheMethod() 
    { 
     Console.WriteLine("I1"); 
    } 

    void I2.TheMethod() 
    { 
     Console.WriteLine("I2"); 
    } 

但請記住,明確的實現不能公開。您可以明確地實現一個,並將另一個作爲可以公開的默認值。

void I1.TheMethod() 
    { 
     Console.WriteLine("I1"); 
    } 

    public void TheMethod() 
    { 
     Console.WriteLine("Default"); 
    } 

查看詳情,請點擊the msdn article

+0

我看看msdn。它現在有點合理。我不認爲我需要明確的實現。只有一個就足夠了。 – user758055 2011-05-17 22:17:10

1

只要方法簽名相同,對於實現兩個或多個接口方法的方法來說,這是完全合法的。

沒有辦法知道「通過哪個接口」調用某個方法 - 沒有這樣的概念(也沒關係)。

3

您不用調用它的接口。一個接口只是一個定義你可以調用哪些方法的契約。你總是調用實現。

0

真正的問題是,「誰在乎它使用的是哪個接口?」真的,它不是「使用」界面。它使用實現來實現接口。

5

如果兩種方法都是公共的,那麼無論調用哪個接口,都會調用同一個方法。如果您需要更多的粒度,則需要使用顯式接口實現:

class TheClass : I1, I2 
{ 
    void I1.TheMethod() {} 
    void I2.TheMethod() {} 
} 

使用可能看起來像:

TheClass theClass = new TheClass(); 
I1 i1 = theClass; 
I2 i2 = theClass; 

i1.TheMethod(); // (calls the first one) 
i2.TheMethod(); // (calls the other one) 

有一點要記住的是,如果你讓實現明確的,您將不再能夠調用TheMethod在聲明爲TheClass變量:

theClass.TheMethod(); // This would fail since the method can only be called on the interface 

當然,如果你願意,你可以明確地只實現其中一個實現,並保持另一個公開,在這種情況下調用TheClass將調用公共版本。

0

這是無關緊要的。投射到任何接口都會導致被調用的方法,但由於接口不能包含代碼,因此不能從中繼承行爲。

2

如果您實例化類,那麼您沒有使用任何接口。如果您將引用強制轉換爲任一接口,那麼您正在使用該接口。例如:

TheClass c = new TheClass(); 
c.TheMethod(); // using the class 

I1 i = new TheClass(); 
i.TheMethod(); // using the I1 interface 

當您的類聲明時,兩個接口都將使用相同的方法。如果僅指定接口的方法

class TheClass : I1, I2 
{ 
    void TheMethod() {} // used by the class 
    void I1.TheMethod() {} // used by the I1 interface 
    void I2.TheMethod() {} // used by the I2 interface 
} 

,除非你投的參考接口首先你無法到達的方法:你也可以指定類和方法的不同接口

class TheClass : I1, I2 
{ 
    void I1.TheMethod() {} // used by the I1 interface 
    void I2.TheMethod() {} // used by the I2 interface 
} 

如果指定只某些接口不同的方法,其他的接口將使用相同的實現作爲類:

class TheClass : I1, I2 
{ 
    void TheMethod() {} // used by the class and the I1 interface 
    void I2.TheMethod() {} // used by the I2 interface 
} 
0
public interface IA 
{ 
    void Sum(); 
} 

public interface IB 
{ 
    void Sum(); 
} 

public class SumC : IA, IB 
{ 
    void IA.Sum() 
    { 
     Console.WriteLine("IA"); 
    } 

    void IB.Sum() 
    { 
     Console.WriteLine("IB"); 
    } 
    public void Sum() 
    { 
     Console.WriteLine("Default"); 
    } 
} 

public class MainClass 
{ 
    static void Main() 
    { 
     IA objIA = new SumC(); 
     IB objIB = new SumC(); 
     SumC objC = new SumC(); 

     objIA.Sum(); 
     objIB.Sum(); 
     objC.Sum(); 

     Console.ReadLine(); 
    } 
} 
+0

顯式實現不能公開..您需要將Default方法設置爲public .. – 2016-05-30 06:37:21

相關問題