为对象定义属性而不是直接访问私有(private)变量有什么好处?
代替:
public class A
private _x as integer = 0
Public property X() as integer
Get
return _x
End Get
Set(ByVal value As integer)
_x = value
End Set
End Property
end class
为什么我们不能做以下事情:
public class A
public _x as integer = 0
end class
有什么好处?
最佳答案
一个好处是许多框架出于绑定(bind)目的寻找类的属性,而不是字段。因此,当您想知道为什么框架没有按照您的预期设置值时,直接公开 _x
字段会引起一些麻烦。
此外,由于封装,您可以更改调用代码与字段交互时发生的情况。将字段隐藏在属性 getter/setter 后面允许您执行其他操作,例如在值更改时触发、更新其他内部状态或完全更改实现以便它只是对子对象的包装调用。
关于c# - 公共(public)属性(property)定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3200664/