gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:05 25 4
gpt4 key购买 nike

我发现自己只想在变量发生变化时才在我的程序中做某些事情。到目前为止,我一直在做这样的事情:

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;
}
}
}

关于java - 如何检测变量是否已更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com