2013-06-20 83 views
4

我有如下的界面:與功能範圍C#接口問題

public interface IInterface 
{ 
    void Open(); 
    void Open(bool flag); 
    void Open(bool flag, bool otherFlag); 
} 

現在實現接口我有以下時:

public class IClass : IInterface 
{ 
    void IInterface.Open() 
    { 
     Open(false, false); 
    } 

    void IInterface.Open(bool flag) 
    { 
     Open(flag, false); 
    } 

    void IInterface.Open(bool flag, bool otherFlag) 
    { 
     //Do some stuff 
    } 
} 

現在,我遇到的問題是,內IClass中的前兩個函數體,我不能調用第三個函數。我得到的錯誤:

The name 'Open' does not exist in the current context

好了,所以我明確地實現接口(由於從其他球隊在組織的要求),然後我得到了「開放」上下文問題。 我可以從三個打開的​​方法中移除顯式的IInterface,然後我可以成功編譯,即使使用其他方法(此處未列出)也可以顯式執行,但我不確定這是什麼意思。

有沒有辦法在明確實現接口方法的同時調用第三種方法?

謝謝!

回答

7

明確的實現需要使用直接參考接口類型,即使在執行類內:

void IInterface.Open() 
    { 
     (this as IInterface).Open(false, false); 
    } 

    void IInterface.Open(bool flag) 
    { 
     (this as IInterface).Open(flag, false); 
    } 

另一種方式保留了明確的實現是電話委託給私有方法:

private void Open(bool flag, bool otherFlag) 
    { 
     // Do some stuff. 
    } 

您的來電都會映射到這個方法:

void IInterface.Open() 
    { 
     Open(false, false); 
    } 
    void IInterface.Open(bool flag) 
    { 
     Open(flag, false); 
    } 
    void IInterface.Open(bool flag, bool otherFlag) 
    { 
     Open(true, true); 
    } 

還要注意的是你的類名違背慣例,刪除前綴I

3

你可以這樣做:

你可以考慮正在對 IInterface,而不是其他重載擴展方法
((IInterface)this).Open(false, false); 

一件事重新實施他們每一次:

public static void Open(this IInterface iface, bool flag) 
{ 
    iface.Open(flag, false); 
} 
1

只要確保你的明確論述this對象的接口由第一投射它:

void IInterface.Open(bool flag) 
{ 
    ((IInterface)this).Open(flag, false); 
} 
1
void IInterface.Open() 
{  
    (this as IInterface).Open(false, false); 
}