我在Embarcadero C++Builder XE8中使用了以下代码。
在单元 1.h 中:
private:
void SetValue (Currency value);
Currency FValue;
public:
__property Currency Value = {write= SetValue , read=FValue};
在单元 1.cpp 中:
void TForm1::SetValue(Currency _Value)
{
FValue= _Value;
Label1->Caption= _Value;
}
在主程序中,当我调用:
Value = 10; // it calls SetValue and the Value will be set to 10
Value+= 10; // it does not call SetValue and Value will not be set to 20
Value+= 10
为什么不打电话给SetValue(20)
?
不能将复合赋值运算符与属性一起使用。 编译器没有实现这一点,也从来没有实现过。
Value = 10;
是直接赋值,因此它会按预期调用属性的 setter。
Value += 10;
不会像您期望的那样转化为Value = Value + 10;
。它实际上调用属性的 getter 来检索临时值,然后将临时值递增并分配给自身。 临时永远不会分配回属性,这就是不调用属性的 setter 的原因。 换句话说,它转化为 temp = Value; temp += 10;
.
若要执行正在尝试的操作,必须分别显式使用 +
和 =
运算符:
Value = Value + 10;