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 ?

21755 次浏览

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.