hash_and_equals
如果重写 ==
,始终重写 hashCode
。
详情
#务必在重写 ==
时重写 hashCode
,并且如果重写 hashCode
,则最好也重写 ==
。
Dart 中的每个对象都有一个 hashCode
。为了使通用的哈希映射实现正常运行,对象的 ==
运算符和 hashCode
属性必须保持一致。因此,当重写 ==
时,也应该重写 hashCode
以保持一致性。 同样,如果重写了 hashCode
,也应该重写 ==
。
错误示例
dart
class Bad {
final int value;
Bad(this.value);
@override
bool operator ==(Object other) => other is Bad && other.value == value;
}
正确示例
dart
class Better {
final int value;
Better(this.value);
@override
bool operator ==(Object other) =>
other is Better &&
other.runtimeType == runtimeType &&
other.value == value;
@override
int get hashCode => value.hashCode;
}
启用
#要启用 hash_and_equals
规则,请在你的 analysis_options.yaml
文件中的 linter > rules 下添加 hash_and_equals
analysis_options.yaml
yaml
linter:
rules:
- hash_and_equals
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 hash_and_equals: true
analysis_options.yaml
yaml
linter:
rules:
hash_and_equals: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。