test_types_in_equals
測試 operator ==(Object other)
中參數的類型。
此規則自 Dart 2.0 起可用。
詳細資訊
#務必在 operator ==(Object other)
中測試參數的類型。
不測試類型可能會導致執行階段類型錯誤,這對於您的類別的使用者來說是意料之外的。
錯誤範例
dart
class Field {
}
class Bad {
final Field someField;
Bad(this.someField);
@override
bool operator ==(Object other) {
Bad otherBad = other as Bad; // LINT
bool areEqual = otherBad != null && otherBad.someField == someField;
return areEqual;
}
@override
int get hashCode {
return someField.hashCode;
}
}
正確範例
dart
class Field {
}
class Good {
final Field someField;
Good(this.someField);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is Good &&
this.someField == other.someField;
}
@override
int get hashCode {
return someField.hashCode;
}
}
用法
#若要啟用 test_types_in_equals
規則,請在您的 analysis_options.yaml
檔案中的 linter > rules 下方新增 test_types_in_equals
analysis_options.yaml
yaml
linter:
rules:
- test_types_in_equals
除非另有說明,否則本網站上的文件反映 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視原始碼 或回報問題。