内容

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 文件中将 test_types_in_equals 添加到 **linter > rules** 下。

analysis_options.yaml
yaml
linter:
  rules:
    - test_types_in_equals