假设我有一个类,它有许多实例变量,.我想重载==运算符(和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类提供的==运算符来执行此操作?

推荐答案

您正在寻找"identical",它将判断两个实例是否相同.

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
}

Dart相关问答推荐

为什么在穷举switch 表达式中需要显式向下转换?

Dart中的运算符(){…}做什么?

Dart 可空记录与模式匹配:(String, int)?类型的匹配值无法分配给所需类型(Object?, Object?)

Dart:判断泛型函数的类型 T

修复了 Flutter Dart 上 DataTable 的列和行标题

Flutter ButtonRow 填充

有没有办法在Flatter中使用PageView实现无限循环?

替换 Flutter 中的片段等小部件

Flutter:并非所有本地化代表都支持应用程序的语言环境

如何在flatter中使用SQFlite更新数据库表

Firebase Crashlytics 崩溃未报告给 Flutter 中的 Firebase 控制台

如何在Dart中处理JSON

Flutter:出现键盘时背景图像正在挤压

Dart 2:Future 和 Future 之间的区别

可选参数的默认值

安装 dart-sdk 后找不到 pub 命令

在 Dart 中,List.from 和 .of 以及 Map.from 和 .of 有什么区别?

具有列表的 Null 感知运算符

用于 dartlang 的 REPL

Dart 中的with关键字