Java2C# 翻译:C# 中接口中的公共方法
另一个翻译问题,这可能更理论化,但我对设计选择很好奇。 SFNQ:
为什么 C# 不允许像 Java 那样控制对接口中方法的访问? 例如,在 C# 界面中:
public void Visit(Axiom axiom);
谢谢。
Another translation question, this may be more theoretical, but I am curious as to the design choice. SFNQ:
Why does C# not allow controlling for controlling access to methods in interfaces like Java does? For example, in a C# interface:
public void Visit(Axiom axiom);
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,在 C# 和 .Net 中,接口上的所有方法默认都是公共的。 没有办法限制他们的访问。
考虑另一种选择,接口上有受保护的成员意味着什么? 您将如何建立访问规则以允许或禁止接口的调用者访问特定方法? (我的意思是 C# 意义上的 protected,而不是 java 意义上的 protected)。
更好的是,私人意味着什么?
In C#, and .Net in general, all methods on an interface are public by default. There is no way to restrict their access.
Consider the alternative, what would it mean to have a protected member on an interface? How would you establish the access rules to allow or disallow a caller of an interface access to the particular method? (I mean protected in the C# sense, not the java one).
Even better, what would private mean?
在 C# 和 Java 中,接口上的所有方法都是公共的。
在 Java 中,允许使用 public 关键字,这可能会节省解析规则。 在 C# 中,public 关键字被认为是多余的,并从接口声明中完全删除。
In both C# and Java, all methods on an interface are public.
In Java, the public keyword is allowed, likely to save on parsing rules. In C#, the public keyword was considered redundant and was removed from interface declarations altogether.
在 C# 中,接口的所有成员都必须是公共的,因此它不允许您向成员声明添加任何可见性修饰符。 因此,public 关键字是多余的并且不需要(事实上,如果包含它,您将收到编译器错误)。
接口是一个契约,它规定您将提供接口定义中指定的所有功能。 如果您被允许在接口中拥有私有成员,您就不会公开该功能(因此您将违反合同)。
In C# all members of an interface must be public, therefore it will not allow you to add any visibility modifiers to the member declarations. The public keyword is therefore redundant and not needed (infact if you include it you'll get a compiler error).
An interface is a contract which states that you will provide all of the functionlity specified in the interface definition. If you were allowed to have private members in an interface you would not be exposing that functionality (and you would therefore violate the contract).