2009-06-17 75 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 
    } 
} 

这里你使用明确的接口实现,以避免尝试根据返回类型重载。