为什么要明确写“私有”?
由于字段是隐式私有的,为什么书籍、文章等中经常使用显式声明?
As fields are implicitly private, why there is often explicit declaraion used in the books, articles etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
因为默认访问级别因语言而异,并且许多人使用不止一种语言进行编程。无论是作为作者还是作为后来阅读代码的人,都很容易感到困惑,因此显式比隐式更好处理。
Because default access levels vary across languages, and many people program in more than one language. It's easy to become confused, either as the author or as someone reading the code later, thus explicit is nicer to deal with than implicit.
隐式声明的问题在于,读者无法判断编写代码的人是否想要隐式声明,或者只是忘记编写任何内容。通过明确表达,其意图是毫无疑问的。
The problem with implicit declarations is that the reader cannot tell if whoever wrote the code wanted the implicit declaration or simply forgot to write anything. By being explicit there's no doubt about the intentions.
为了让你的代码看起来不错:)。
你是对的,这不是必需的,但无论如何编写它们是习惯。至少,每个方法都有明确指出的特权,它使您的代码更易于阅读。
To make your code look nice :).
You're right it's not necessary, but it's custom to write them anyway. At the very least, every method has a privilege explicitly noted and it makes your code easier to read.
有时,明确的比隐含的更好,当您编写教育材料时更是如此。对于不知道或记不住默认访问级别规则的人来说,在阅读代码时就少了一件需要关心的事情。
相关问题
Sometimes explicit is better than implicit, and this is even more so when you are writing educational material. For people who do not know or cannot remember the rules for the default access levels it is one less thing for them to be concerned with when reading the code.
Related Question
因为您编写代码是为了可维护性和清晰度,尤其是在代码示例中。隐式声明是为编译器提供的,而不是为程序员提供的。未能显式声明变量的可见性和范围会使您的意图不明确。真的有那么多额外的打字吗?
Because you write code for maintainability and clarity, ESPECIALLY in code samples. Implicit declarations are there for the compiler, not for the programmer. Failing to explicitly declare the visibility and scope of your variables leaves your intent ambiguous. Is it really that much extra typing?
你必须记住,代码最终可能会在某个时候被其他人阅读,6 个月后可能是你,并且你需要理解其意图。声明某些内容为私有意味着您不希望所有可能使用它的人都可以使用该特定的实现细节(此时),以后的修订可能会改变特定事物的工作方式,并且如果您希望提供向后兼容性,如果它从一开始就是公开的,那么它需要保留在未来的修订中。
You have to remember that code can end up with someone else to reading it at some point, it might be you in 6 months and you need to understand the intent. Declaring something private means that you are not wanting that particular implementation detail to be available to all those who may use it(at this point in time), later revisions may change the way that particular thing works and if you wish to provide backward compatibility, if it's been public from the begining, it needs to remain in future revisions.
在我看来,它使代码更具可读性。我不必考虑默认的访问修饰符。
它也由 StyleCop 强制执行,这是我用来确保一致的编码风格的工具。
In my opinion it makes the code better readable. I don't have to think about the default access modifier.
It's also enforced by StyleCop, a tool I use to ensure a consistent coding style.
显式声明用来告诉你该变量是故意设置为私有的,需要将其声明为私有
Explicit declaration used to told you that the variable is deliberately set to private and it needs to be declare as private