How to detect if a variable has changed?

前端 未结 6 1367
生来不讨喜
生来不讨喜 2020-12-10 06:16

I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:

int x = 1;
in         


        
6条回答
  •  悲哀的现实
    2020-12-10 06:50

    Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:

    public class X
    {
        private int x = 1;
    
        //some other code here
    
        public void setX(int proposedValueForX)
        {
           if(proposedValueForX != x)
           {
               doOneTimeTaskIfVariableHasChanged();
               x = proposedValueForX;
           }
        }
    }
    

提交回复
热议问题