37

假设我有一个有很多实例变量的类。我想重载 == 运算符(和 hashCode),以便可以将实例用作映射中的键。

class Foo {
  int a;
  int b;
  SomeClass c;
  SomeOtherClass d;
  // etc.

  bool operator==(Foo other) {
    // Long calculation involving a, b, c, d etc.
  }
}

比较计算可能很昂贵,因此我想检查是否与进行该计算之前other的实例相同。this

如何调用 Object 类提供的 == 运算符来执行此操作?

4

4 回答 4

49

您正在寻找“相同”,它将检查 2 个实例是否相同。

identical(this, other);

更详细的例子?

class Person {
  String ssn;
  String name;

  Person(this.ssn, this.name);

  // Define that two persons are equal if their SSNs are equal
  bool operator ==(Person other) {
    return (other.ssn == ssn);
  }
}

main() {
  var bob = new Person('111', 'Bob');
  var robert = new Person('111', 'Robert');

  print(bob == robert); // true

  print(identical(bob, robert)); // false, because these are two different instances
}
于 2013-08-25T12:04:52.753 回答
6

您可以使用identical(this, other).

于 2013-08-25T12:05:58.880 回答
2

为了完整起见,这是对现有答案的补充答案。

如果某个类Foo没有覆盖,那么==默认实现是返回它们是否是同一个对象。该文档指出:

所有对象的默认行为是当且仅当此对象和其他对象是同一个对象时才返回 true。

于 2021-10-11T07:01:26.930 回答
0

在不同但相似的情况下,如果框架调用检查对象之间的相等性,例如list.toSet()从列表中获取唯一元素的情况,identical(this, other)可能不是一种选择。那个时候类必须覆盖== operatorhasCode()方法。

但是,对于这种情况,另一种方法可能是使用equatable包。这可以节省大量样板代码,并且在您有很多模型类时特别方便。

于 2021-01-18T17:56:03.290 回答