简体   繁体   English

为什么我不能在接口中声明公共方法?

[英]Why can't I declare a public method in an interface?

Why doesn't the compiler like that I declare a public method in a class interface (this caused the error I got here .NET Class Interface, Inheritance and Library: error does not implement interface member ).为什么编译器不像我那样在类接口中声明一个公共方法(这导致了我在这里得到的错误.NET Class Interface, Inheritance and Library: error does not implement interface member )。

Is it just because of syntax or because of something more fundamental ?是因为语法还是因为一些更基本的东西?

OK it's implicit but why would it hurt to make it explicit ?好的,它是隐含的,但为什么让它明确会受到伤害?

Interface is a contract and anywhere where you can access the interface, you should be able to access all the methods in it.接口是一个契约,在任何可以访问接口的地方,您都应该能够访问其中的所有方法。 In other words, all the methods declared in the interface are supposed to be public so it doesn't make sense stating it explicitly.换句话说,接口中声明的所有方法都应该是公共的,因此明确说明它是没有意义的。

接口方法是隐式公开的,因此将它们声明为公开是多余的。

Since C# 8 things are a bit different.由于 C# 8 事情有点不同。 public modifier is now allowed.现在允许使用public修饰符。 I suggest reading this article .我建议阅读这篇文章

Check this out 看一下这个

Thought it is for constants, I think this is what language designers were thinking why not to permit Public in interface.以为是常量,我想这就是语言设计者在想为什么不允许在接口中使用 Public 的原因。

You cannot use any access modifiers in interfaces (eg private, partial).您不能在接口中使用任何访问修饰符(例如私有、部分)。 This is because it's the implementing class's responsibility to mark the accessibilty of the methods.这是因为标记方法的可访问性是实现类的责任。 It keeps the purpose of interfaces singular, which is to define the signature of the class, not to define its access restriction.它保持接口的单一目的,即定义类的签名,而不是定义其访问限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 继承接口的方法不能明确地声明为“公共” - Inherited Interface's Method Can't Be Explicitly Declare as “Public” 为什么我不能声明通用列表 <T> 作为接口方法的返回类型? - Why can't I declare generic List<T> as return type for interface method? 为什么我不能将逆变接口作为接口上的方法的参数? - Why can't I take a contravariant interface as a parameter to a method on the interface? 我可以声明一个接口方法来返回C#中的通用接口吗? - Can I declare an interface method to return generic Interface in C#? 为什么我不能在另一个类中调用公共方法? - Why can't I call a public method in another class? 为什么我不能用返回具体类型的方法实现返回接口的接口方法 - Why can't I implement an interface method that returns an interface with a method that returns a concrete type 如何确定接口上哪个类称为公共方法? - How can I determine which class called a public method on an interface? 为什么我的界面没有实现公共方法? - Why will my interface not implement a public method? 当对象属于子类类型时,为什么不能在超类的子类中调用公共方法? - Why can't I call a public method in the subclass from the superclass when the object is of the subclass type? 为什么我不能在接口上调用ToString()? - Why can't I call ToString() on an interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM