简体   繁体   English

为什么显式实现接口不能公开?

[英]Why Explicit Implementation of a Interface can not be public?

I have method in Class which is implementation of Interface. 我在Class中有方法,它是Interface的实现。 When I made it Explicit implementation I got compiler error 当我做它显式实现时,我遇到了编译器错误

The modifier 'public' is not valid for this item

Why it is not allowed to have public for explicit interface implementation ? 为什么不允许public显示接口?

The reason for an explicit interface implementation is to avoid name collisions with the end result being that the object must be explicitly cast to that interface before calling those methods. 显式接口实现的原因是避免名称冲突,最终结果是在调用这些方法之前必须将对象显式地转换为该接口。

You can think of these methods not as being public on the class, but being tied directly to the interface. 您可以认为这些方法不是在类上公开,而是直接绑定到接口。 There is no reason to specify public/private/protected since it will always be public as interfaces cannot have non-public members. 没有理由指定public / private / protected,因为它总是公开的,因为接口不能有非公共成员。

(Microsoft has an overview on explicit interface implementation ) (Microsoft 概述了显式接口实现

The explict member implementation allow disambiguation of interface members with the same signature. 明确的成员实现允许消除具有相同签名的接口成员的歧义。

Without explict interface member implementations it would be impossible for a class or a structure to have different implementations of interface members with the same signature and return type. 如果没有明确的接口成员实现,那么类或结构就不可能具有相同签名和返回类型的接口成员的不同实现。

Why Explicit Implementation of a Interface can not be public? 为什么显式实现接口不能公开? When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. 显式实现成员时,不能通过类实例访问它,而只能通过接口的实例访问它。

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();
.....

Explict interface member implementations are not accessible through class or struct instances. 无法通过类或结构实例访问Explict接口成员实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM