C#:在实现方法中显式指定接口(interface)

标签 c# interface access-modifiers

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

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

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

那么,为什么在方法为私有(private)时必须显式指定接口(interface),而在方法为公共(public)时则不必?

最佳答案

显式接口(interface)实现是一种介于公共(public)和私有(private)之间的折衷办法:如果您使用接口(interface)类型的引用来访问它,它就是公共(public)的,但这是唯一访问方式它(即使在同一个类(class))。

如果您使用的是隐式接口(interface)实现,则需要将其指定为公共(public)方法,因为它是一个公共(public)方法,由于它在接口(interface)中,您可以覆盖它。换句话说,有效代码是:

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

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

我个人很少使用显式接口(interface)实现,除非像 IEnumerable<T> 这样的事情需要它。 GetEnumerator 有不同的签名基于它是通用接口(interface)还是非通用接口(interface):

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

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

在这里,您必须使用显式接口(interface)实现来避免尝试根据返回类型重载。

关于C#:在实现方法中显式指定接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1006094/

相关文章:

c# - 需要帮助实现接口(interface)

java - Java中 protected 和包私有(private)的访问修饰符之间的区别?

c# 将表单添加到项目: Possible to make it internal/private from designer?

c# - 为什么异步代码在 C# 的工作线程上运行

c# - 将 C# 可执行文件的图标设置为文件处理程序的问题

去反射 panic : Call using interface{} as type

swift - 文件私有(private)扩展名与普通扩展名

c# - 如何将 VS 命令提示符添加到 Visual Studio 2010 C# Express?

c# - SOLID-原则的尝试,实不实?

c# - 在 C# 中为可序列化类型创建接口(interface)?