C#:在实现的方法中明确指定接口

And*_*ech 3 c# interface access-modifiers

为什么在实现接口时,如果我将方法设为公共,我不必显式指定接口,但如果我将其设为私有,我必须...像这样(GetQueryString是IBar的方法):

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

    //But this does:
    string IBar.GetQueryString() 
    {
        ///...
    }
}
Run Code Online (Sandbox Code Playgroud)

那么为什么在私有方法时必须明确指定接口,而不是在方法公开时?

Jon*_*eet 11

显式接口实现是公共和私有之间的一种中途:如果你使用接口类型引用来获取它,它是公共的,但这是访问它的唯一方法(即使在同一个类中).

如果您正在使用隐式接口实现,则需要将其指定为public,因为它一个公共方法,因为它位于接口中而被覆盖.换句话说,有效代码是:

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

    // Explicit implementation - no access modifier is allowed
    string IBar.GetQueryString() 
    {
        ///...
    }
}
Run Code Online (Sandbox Code Playgroud)

就个人而言,我很少使用显式接口实现,除非根据它是通用接口还是非通用接口,它需要IEnumerable<T>具有不同签名的东西GetEnumerator:

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

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Call to the generic version
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,您必须使用显式接口实现,以避免尝试基于返回类型重载.