提问人:Scorb 提问时间:12/13/2020 最后编辑:creativecreatorormaybenotScorb 更新时间:12/13/2020 访问量:339
Dart 对象的默认 == 行为是什么?
What is the default == behavior for Dart objects?
问:
我有以下飞镖课......
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';
}
我没有实现 == 运算符。
当我在这些对象的两个实例上使用 == 运算符时会发生什么?
答:
1赞
creativecreatorormaybenot
12/13/2020
#1
它将检查实例是否引用相同的对象。
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
Object
Object?
null
如果你看一下 Object.==
实现),你会看到它很简单:
external bool operator ==(Object other);
以下是其行为方式的快速摘要:这两个对象必须是完全相同的对象。
identical
我很确定相同的
功能以完全相同的方式运行,即使文档中的措辞略有不同:
检查两个引用是否指向同一对象。
hashCode
重写对默认实现没有影响,因为它将始终使用 identityHashCode
。hashCode
==
了解有关 Object.hashCode
的更多信息。
评论