是否有原因无法在方法或接口中定义访问修饰符?
方法可见性的责任被委托给实现该接口的类。
public interface IMyInterface
{
bool GetMyInfo(string request);
}
在 C# 中,在方法 GetMyInfo() 生成以下错误之前设置访问修饰符 public、private 或 protected:修饰符“private”对此项无效。
是否有原因无法在方法或接口中定义访问修饰符?
(已在此处用法语提出问题)
The responsibility of the visibility of a method is relegated to the class that implements the interface.
public interface IMyInterface
{
bool GetMyInfo(string request);
}
In C# set access modifier public, private or protected before the method GetMyInfo() generates the following error: The modifier 'private' is not valid for this item.
Is there a reason you can not define the access modifier on a method or in an interface?
(Question already asked in french here)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该接口定义了对象和调用其成员的客户端之间的契约。私有方法不能被任何其他对象访问,因此将其添加到接口中没有意义。因此,接口的所有成员都被视为公共成员。
The interface defines a contract between an object and clients that call its members. A private method cannot be accessed by any other objects so it doesn't make sense to add it to the interface. All members of an interface are considered public for this reason.
如果您进行显式接口实现,您实际上可以在实现类中将该方法设为私有:
此方法意味着
GetMyInfo
将不会成为我的班级
。只能通过将MyClass
实例转换为IMyInterface
来访问它:因此,在接口的上下文中,其所有成员都将是公共的。它们可以对实现类的公共接口隐藏,但始终可以对实例进行类型转换并以这种方式访问成员。
You can actually make the method private in the implementing class, if you make an explicit interface implementation:
This approach means that
GetMyInfo
will not be part of the public interface ofMyClass
. It can be accessed only by casting aMyClass
instance toIMyInterface
:So, in the context of the interface, all its members will be public. They can be hidden from the public interface of an implementing class, but there is always the possibility to make a type cast to the instance and access the members that way.
从面向对象的角度来看——封装就是数据隐藏。这意味着类内部发生的任何事情都取决于类的实现。这意味着通过合同强制执行私人成员是没有用的。
然而,使用接口的原因是因为您希望确保类遵守特定的契约并以一致的方式公开多个公共成员。
In terms of OO - encapsulation is all about data hiding. That means whatever goes on inside a class is up to the class implementation. Which means it would be useless to contractually enforce private members.
However, the reason one uses interfaces is because you want to ensure a class adheres to a specific contract and exposes several public members in a consistent way.
接口的所有方法必须具有相同的访问级别 - 以便调用者可以使用所有这些方法。但是,接口也可以是内部的(或作为嵌套接口私有)。
如果您需要不同的访问级别,请使用不同的界面。
All of the methods of an interface must have the same access level - so that the caller may use all of them. However interfaces can also be internal (or as nested interface private).
If you need different access levels use a distinct interface.
接口中的私有定义将:
A private definition in the interface would: