hash_and_equals
如果覆寫 ==
,請務必覆寫 hashCode
。
此規則自 Dart 2.0 起可用。
此規則有可用的快速修正。
詳細資訊
#如果覆寫 ==
,請覆寫 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
除非另有說明,否則本網站上的文件反映的是 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視來源 或 回報問題。