属性获取器是否应返回私有成员以外的其他值? [英] Should property getters return values other than that of the private member?
问题描述
private int _myField;
public int MyField
{
get {
return _myField * 99;
}
set {
_myField * value;
}
}
我已经看到开发人员在其中添加了更复杂的代码Getter,设置其他成员和属性等。对我来说,返回除关联成员变量以外的值会导致调试混乱。
I've seen developers add more complex code into the Getter, setting other members and properties etc. To me return a value other than the associated member variable causes debugging confusion.
$ b $更好吗?
private int _myField;
public int MyField
{
get {
return _myField = _myField * 99;
}
set {
_myField * value;
}
}
还是这个?
private int _myField;
public int MyField
{
get {
return _myField;
}
set {
_myField = value * 99;
}
}
推荐答案
I认为您的第二个片段完全违反了代码的语义。使用吸气剂不应影响公共价值-也就是说,您可以在吸气剂内部进行任何您想做的事情,例如缓存或延迟初始化等-但在外部,两次连续调用吸气剂应返回相同的结果。
I think your second snippet is quite a violation of the code's semantics. Using a getter should not influence the public value - that is, you can do whatever you want inside the getter, such as caching or lazy initialisation and so on - but in the outside, two consecutive calls to the getter should return the same result.
这篇关于属性获取器是否应返回私有成员以外的其他值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!