如何检测变量是否已更改?

Amplify91:

我发现自己只想在变量已更改的情况下在程序中执行某些操作。到目前为止,我一直在做这样的事情:

int x = 1;
int initialx = x;

...//code that may or may not change the value of x

if (x!=initialx){
    doOneTimeTaskIfVariableHasChanged();
    initialx = x; //reset initialx for future change tests
}  

有没有更好/更简单的方法可以做到这一点?

占士邦 :

由于您只想在值更改时查找并执行某些操作,因此我将使用setXXX,例如:

public class X
{
    private int x = 1;

    //some other code here

    public void setX(int proposedValueForX)
    {
       if(proposedValueForX != x)
       {
           doOneTimeTaskIfVariableHasChanged();
           x = proposedValueForX;
       }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章