2009-06-17 76 views
3

爲什麼在實現接口時,如果我公開該方法,則不必明確指定接口,但如果我將其設爲私有,則必須...像這樣的(GetQueryString是伊巴爾的方法):C#:在實現的方法中明確指定接口

public class Foo : IBar 
{ 
    //This doesn't compile 
    string GetQueryString() 
    { 
     ///... 
    } 

    //But this does: 
    string IBar.GetQueryString() 
    { 
     ///... 
    } 
} 

那麼,爲什麼你必須明確地,當該方法是由私人指定接口,而不是當該方法是公開的?

+0

當你說不起作用,你的意思是 - 不編譯或不按預期運行? – 2009-06-17 09:57:46

+0

不能編譯 – 2009-06-17 10:05:19

回答

11

明確的接口實現是公共和私人之間的一種中介:如果您使用接口類型的引用來獲取接口,那麼它是公開的,但這只是的訪問方式(即使在同一班)。

如果您使用隱式接口實現,則需要將其指定爲公共,因爲它是因爲它在接口中而被覆蓋的公共方法。換句話說,有效的代碼是:

public class Foo : IBar 
{ 
    // Implicit implementation 
    public string GetQueryString() 
    { 
     ///... 
    } 

    // Explicit implementation - no access modifier is allowed 
    string IBar.GetQueryString() 
    { 
     ///... 
    } 
} 

我個人,除非它需要的東西像IEnumerable<T>其中有基於它是否是通用或非通用接口GetEnumerator不同的簽名很少使用顯式接口實現

public class Foo : IEnumerable<string> 
{ 
    public IEnumerator<string> GetEnumerator() 
    { 
     ... 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); // Call to the generic version 
    } 
} 

這裏你使用明確的接口實現,以避免嘗試根據返回類型重載。