这是示例:

if(value != ageValue) {
  ageValue = value;
}

我的意思是,如果我们将一个变量的值分配给另一个变量,为什么还要检查它们是否具有相同的值?

这让我感到困惑。这里是更广泛的上下文:
private double ageValue;
public double Age {
  get {
    return ageValue;
  }

  set {
    if(value != ageValue) {
      ageValue = value;
    }
  }
}

最佳答案

当检查非常有用时,这是一个代码示例:

 public class MyClass {
    ...
    int ageValue = 0;

    public int AgeValue {
      get {
        return ageValue
      }
      protected set {
        ... // value validation here

        // your code starts
        if (value != ageValue) {
          ageValue = value;
        }
        // your code ends
        else
          return; // do nothing since value == ageValue

        // ageValue has been changed
        // Time (or / and memory) consuming process
        SaveToRDBMS();
        InvalidateCache();
        ...
      }
    }

 ...

但是,更自然的实现是从一开始就进行检入,以避免不必要的计算。
    protected set {
      if (ageValue == value)
        return;

      ... // value validation here
      ageValue = value;

      // ageValue has been changed
      // Time (or / and memory) consuming process
      SaveToRDBMS();
      InvalidateCache();
      ...
    }

10-02 06:01