Dart 对象的默认 == 行为是什么?

What is the default == behavior for Dart objects?

我有以下飞镖class...

class Color {
  final int value;
  const Color._internal(this.value);

  static const Color WHITE = const Color._internal(0);
  static const Color BLACK = const Color._internal(1);

  int get hashCode => value;
  String toString() => (this == WHITE) ? 'W' : 'B';
}

我还没有实现 == 运算符。

当我在这些对象的两个实例上使用 == 运算符时会发生什么?

它将检查实例是否 引用 相同的对象

Color._internal(0) == Color._internal(0); // false
const Color._internal(0) == const Color._internal(0); // true

final foo = Color._internal(1);
foo == Color._internal(2); // false
foo == Color._internal(1); // false
foo == foo; // true

因此,对于 const 个引用,它仅对同一个变量(或传递该引用时)为真。

Object.==

默认的 == 实现是 Object.==,因为您的 Color class 本质上低于 classes Object(或 Object?null).

如果你看一下 the Object.== implementation),你会发现它很简单:

external bool operator ==(Object other);

以下是其行为方式的简要总结:两个对象需要 完全相同的对象

identical

我很确定 identical fuction 的行为方式完全相同,即使文档中的措辞略有不同:

Check whether two references are to the same object.

hashCode

覆盖 hashCode 对默认 == 实施没有影响,因为它将始终使用 identityHashCode.

详细了解 Object.hashCode