比较对象时,== 运算符在 dart 中究竟如何工作?

How exactly does the == operator work in dart when comparing objects?

所以 Dart API 关于 == 运算符的说法是这样的:

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

Total: It must return a boolean for all arguments. It should never throw.

Reflexive: For all objects o, o == o must be true.

Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

但是如果 2 个对象相同,Dart 究竟如何检查?

return true if and only if this object and other are the same object

可以理解为“检查两个对象是否是对同一实例的引用”,显然不是这样。

所以假设我有 2 个

class Car {
  int tires = 4;
  Color color = Colors.blue;
  int doors = 4;
}

Car carA = Car();
Car carB = Car();

根据我的理解,如果我检查 carA == carB,Dart 会通过循环比较两个实例的所有属性吗?

如果是这样的话,它是否总是深入到基元,例如,如果某些属性是非基元的类?

谢谢

我相信 Dart 确实“检查两个对象是否是对同一实例的引用”。如果要比较属性,可以重写 == 运算符,例如:

class Car {
  int tires = 4;
  int doors = 4;

  @override
   bool operator ==(Object other) {
     return other is Car && this.tires == other.tires && this.doors == other.doors;
   } 
  @override
  int get hashCode => this.tires * this.doors;
}

void main() {
  Car carA = Car();
  Car carB = Car();
  print("equal ${carA==carB}");
  print("identical ${identical(carA,carB)}");
}

现在汽车是平等的。请注意,函数 identical() 会检查同一个对象。

Dart 规范指定常量对象检查属性,例如:

class ConstCar {
  final int tires = 4;
  final int doors = 4;
  const ConstCar();
}

void main() {
  ConstCar constCarA = const ConstCar();
  ConstCar constCarB = const ConstCar();
  print("equal ${constCarA==constCarB}");
  print("identical ${identical(constCarA,constCarB)}");
}

这 returns 对于 ==identical() 是正确的。