test_types_in_equals
测试 operator ==(Object other)
中参数的类型。
详情
#应该 在 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
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 test_types_in_equals: true
analysis_options.yaml
yaml
linter:
rules:
test_types_in_equals: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。