向我解释什么是二传手和吸气剂 [英] Explain to me what is a setter and getter
问题描述
什么是二传手和吸气剂?我为什么需要它们?有效地使用它们的一个好例子是什么? setter和getter的意义是什么?
What are setters and getters? Why do I need them? What is a good example of them in use in an effective way? What is the point of a setter and getter?
更新: 我可以得到一些编码示例吗?
Update: Can I get some coding examples please?
推荐答案
getter是一种获取属性值的方法.设置器是一种设置属性值的方法.关于它们的功效存在一些争论,但要点通常是:
A getter is a method that gets the value of a property. A setter is a method that sets the value of a property. There is some contention about their efficacy, but the points are generally:
-
确保封装的完整性
for completeness of encapsulation
以在内部细节发生变化时保持一致的界面
to maintain a consistent interface in case internal details change
当您需要在获取或设置周围添加一些逻辑(例如在编写值之前对其进行验证)时,更有用.
More useful is when you need to add some logic around getting or setting, like validating a value before you write it.
这篇关于向我解释什么是二传手和吸气剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!