【问题标题】:Why Explicit Implementation of a Interface can not be public?为什么接口的显式实现不能公开?
【发布时间】:2010-11-18 04:54:24
【问题描述】:

我在类中有方法,它是接口的实现。当我让它显式实现时,我得到了编译器错误

The modifier 'public' is not valid for this item

为什么不允许有public 用于显式接口实现?

【问题讨论】:

    标签: c# interface


    【解决方案1】:

    显式接口实现的原因是为了避免名称冲突,最终结果是对象必须在调用这些方法之前显式转换为该接口。

    您可以认为这些方法不是在类上公开的,而是直接绑定到接口的。没有理由指定 public/private/protected,因为它始终是公共的,因为接口不能有非公共成员。

    (微软有一个overview on explicit interface implementation

    【讨论】:

    • 对于隐式接口,也不需要指定为public,但允许这样做,实际上必须这样做。所以暗示公共逻辑的接口并不能真正解释我要说的原始问题。
    • 对于隐式接口,该方法只是一个可以是私有的方法。仅它的签名就使其成为接口方法实现。显式接口定义只能是公开的。我明白你的意思,但是 TBH 允许公开隐式方法可能只与编译器执行操作的顺序有关。
    • "...since it will always be public...";从技术上讲,这是不正确的,因为在将对象转换为接口之前,您无法从外部调用显式实现的函数。
    • @Massood - 他们的可发现性与他们的可访问性无关。成员当然是公共的,因为它们可以从不相关的类访问,而不仅仅是从声明类(私有)、派生类(受保护)或程序集(内部)
    • 这是“公共”定义的问题。我检查了C# language specification。在第 13.4.1 节,第 392 页它说:"Explicit interface member implementations have different accessibility characteristics than other members. Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public."
    【解决方案2】:

    显式成员实现允许消除歧义 具有相同签名的接口成员。

    如果没有明确的接口成员实现,一个类或结构就不可能拥有具有相同签名和返回类型的接口成员的不同实现。

    为什么接口的显式实现不能公开? 当成员显式实现时,不能通过类实例访问,只能通过接口实例访问。

    public interface IPrinter
    {
       void Print();
    }
    public interface IScreen
    {
       void Print();
    }
    
    public class Document : IScreen,IPrinter
    {
        void IScreen.Print() { ...}
        void IPrinter.Print() { ...} 
    }
    
    .....
    Document d=new Document();
    IScreen i=d;
    IPrinter p=d;
    i.Print();
    p.Print();
    .....
    

    无法通过类或结构实例访问显式接口成员实现。

    【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2011-05-05
    • 2010-09-29
    • 2013-11-17
    • 2013-01-17
    • 2015-09-20
    相关资源
    最近更新 更多