构造函数外部和内部变量实例化之间的差异
我必须决定是否将变量放在构造函数内或外部,但我一直感觉缺少信息,我查看了有关堆栈溢出的其他帖子,但都提到这是一个偏好问题,但我发现我认为两个差异可能很重要:
- 如果我决定将变量放在构造函数中,那么我必须为任何希望更改变量的函数提供一个对象参数,即使代码是类的内部代码。
- 子类化会导致变量不出现,当类和任何子类必须具有变量才能正常运行时,这会导致问题。
我可能在所有这些点上都是错的,但在凌晨 4 点,我宁愿被告知我错了,也不愿因为骄傲而犯错。如果这个问题已在其他地方得到回答而我错过了,我很抱歉,如果您可以发布链接,我将不胜感激。
I have to decide whether to put a variable within a constructor or outside, but I keep getting the feeling that I am missing information, I have looked at other posts on stack overflow, but all mentioned it was a matter of preference, yet I found two difference that I feel might be important:
-If I decide to put the variables within a constructor, then I must have an object parameter for any function that wish to alter the variables, even if the code is internal to the class.
-Subclassing would cause the variables to not appear, something that causes problems when the class and any subclasses must have the variables in order to operate properly.
I may be wrong on all of these points, but at 4am, I would rather be told I am wrong than commit a mistake due to pride. If this has been answered somewhere else and I missed it, I am sorry, and if you could post the link, I would be grateful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
构造函数内的操作被解释,所有其他操作都被预编译,因此它们工作得更快
actions inside the constructor are interpreted, all others are precompiled so they work faster
就像 www0z0k 已经说过的那样,构造函数外部的声明被简单地解释,因此在某些情况下在外部声明它们可以提高性能。
这是正确的。
您应该考虑要存档的内容。大多数时候,您应该选择一个好的软件设计,然后再考虑性能。您提到的这个子类化问题还可以保护某些变量不被更改。
问候,
iuiz
Like www0z0k already said, the declarations outside the constructor are merly interpreted, so declaring them outside can be a performance bost under some circumstances.
This is correct.
You should think about what you want to archive. Most times you should rather choose a good software design then to think about performance. This subclassing problem that you mentioned can also protect some variables from being changed.
Greetings,
iuiz
如果我理解正确的话,您正在寻找受保护的字段(或属性)。
抱歉,我不明白...
@Performance:关于解释构造函数的所有内容,您可以在构造函数中添加一个简单的 init(...) 函数,该函数可以完成您在构造函数中执行的所有操作 - 但不会被解释。
If I understood you correctly you're looking for protected fields (or properties).
Sry, I don't get that...
@Performance: with all that said about interpreted constructors you could add a simple init(...) function within your constructor which does all you would do in the constructor - but without being interpreted.