【问题标题】:Enum equalization with other classes枚举与其他类的均衡
【发布时间】:2022-08-19 01:18:50
【问题描述】:

我创建了一个只接受Enums 作为参数的类。我想我可以创建第三个Enum,在那里我会手动放置每个选项,以便它们有更好的命名。

唯一的问题是,我无法仅通过使用 == 运算符来测试我的第三个 Enum 实例和具有相同参数的类实例是否相等。尝试使用equatable 并将Enum 实例视为我的类实例,因为它确实实现了它,但没有任何效果。当然,我可以创建一个所有给定参数都相等的测试,但我只是想知道我是否可以做一些事情,以便在使用== 运算符时返回true

例如。:

配置

enum A {
  a,
  b;
}
enum B {
  c,
  d;
}

class Class with EquatableMixin {
  const EveryDayOfYear({required this.aValue, required this.bValue});

  final A aValue;
  final B bValue;
  
  @override
  List<Object?> get props => [aValue, bValue];
}

enum C {
  ac(Class(aValue: A.a, bValue: B.c)),
  ad(Class(aValue: A.a, bValue: B.d)),
  bc(Class(aValue: A.b, bValue: B.c)),
  bd(Class(aValue: A.b, bValue: B.d));

  const C(this._handler);

  final Class _handler;

  @override
  A get aValue => _handler.aValue;

  @override
  B get bValue => _handler.bValue;

  @override
  List<Object?> get props => [aValue, bValue];
}

客观的

final instance = Class(aValue: A.a, bValue: B.c);
instance == C.ac; // I would like something so this operation returns true.

    标签: dart enums equals equality


    【解决方案1】:

    正如@Levi-Lescheshere所评论的那样,我的问题的答案是覆盖我的operator ==

      @override
      // ignore: hash_and_equals, already implemented by EquatableMixin
      bool operator ==(Object other) {
        return (super == other) ||
            ((other is Class) &&
                (week == other.aValue) &&
                (day == other.bValue));
      }
    

    这解决了我的问题并且是公平的,因为我的类实例不是Enum,但我的枚举常量实际上是我的类实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多