【发布时间】:2010-11-18 04:54:24
【问题描述】:
我在类中有方法,它是接口的实现。当我让它显式实现时,我得到了编译器错误
The modifier 'public' is not valid for this item
为什么不允许有public 用于显式接口实现?
【问题讨论】:
我在类中有方法,它是接口的实现。当我让它显式实现时,我得到了编译器错误
The modifier 'public' is not valid for this item
为什么不允许有public 用于显式接口实现?
【问题讨论】:
显式接口实现的原因是为了避免名称冲突,最终结果是对象必须在调用这些方法之前显式转换为该接口。
您可以认为这些方法不是在类上公开的,而是直接绑定到接口的。没有理由指定 public/private/protected,因为它始终是公共的,因为接口不能有非公共成员。
【讨论】:
"...since it will always be public...";从技术上讲,这是不正确的,因为在将对象转换为接口之前,您无法从外部调用显式实现的函数。
"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."
显式成员实现允许消除歧义 具有相同签名的接口成员。
如果没有明确的接口成员实现,一个类或结构就不可能拥有具有相同签名和返回类型的接口成员的不同实现。
为什么接口的显式实现不能公开? 当成员显式实现时,不能通过类实例访问,只能通过接口实例访问。
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();
.....
无法通过类或结构实例访问显式接口成员实现。
【讨论】: