简体   繁体   中英

Why Explicit Implementation of a Interface can not be public?

I have method in Class which is implementation of 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 ?

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.

(Microsoft has an overview on explicit interface implementation )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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