Dart:将派生类的比较运算符委托给基类的比较运算符

Mat*_*247 6 dart

我想重载 Dart 中的比较运算符 (==) 来比较结构。现在,当我已经重载基类的比较运算符并想要重用它时,我不确定如何为派生类执行此操作。

假设我有一个基类,如:

class Base
{
  int _a;
  String _b;

  bool operator ==(Base other)
  {
    if (identical(other, this)) return true;
    if (_a != other._a) return false;
    if (_b != other._b) return false;
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我声明我的派生类添加了额外的字段,并且还想重载 operator==。我只想比较派生类中的附加字段,并将 Base 字段的比较委托给 Base 类。在其他编程语言中,我可以执行类似Base::operator==(other)或 的操作super.equals(other),但在 Dart 中我不知道什么是最好的方法。

class Derived extends Base
{
  int _c; // additional field

  bool operator ==(Derived other)
  {
    if (identical(other, this)) return true;        
    if (_c != other._c) return false; // Comparison of new field

    // The following approach gives the compiler error:
    // Equality expression cannot be operand of another equality expression.
    if (!(super.==(other))) return false;

    // The following produces "Unnecessary cast" warnings
    // It also only recursively calls the Derived operator
    if ((this as Base) != (other as Base)) return false;    

    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想我能做的是:

  • 比较派生类中的基类的所有字段:如果基类 get 发生更改,则非常容易出错,并且当基类和派生类位于不同的包中时也不起作用。
  • 声明一个equals与当前逻辑相同的函数operator ==,调用super.equals()以比较基类并将所有调用委托operator==给该equals函数。然而,实现equalsoperator ==.

那么这个问题的最佳或推荐解决方案是什么?

Mat*_*247 9

好的,经过一些进一步的实验,我自己弄明白了。它只是调用:

super==(other)
Run Code Online (Sandbox Code Playgroud)

之前super.operator==(other)super.==(other)之前都试过,没想到简单super==(other)就够了。

对于上面给定的示例,正​​确的运算符是:

bool operator ==(Derived other)
  {
    if (identical(other, this)) return true;
    if (_c != other._c) return false;
    if (!(super==(other))) return false;
    return true;
  }
Run Code Online (Sandbox Code Playgroud)

  • 您也可以删除括号:`super == other` (6认同)

Rob*_*b C 5

似乎我正在讨论一个 5 年前的问题,但现在我们有了 Dart 2...

== 运算符可以轻松地内联定义。

class Base {
    int a;
    String b;

    bool operator ==(other) => other is Base
          && other.a == a
          && other.b == b;
}
Run Code Online (Sandbox Code Playgroud)

从派生类重用super == other似乎仍然是一种方法。

class Derived extends Base {
    int c;

    bool operator ==(other) => other is Derived
          && super == other
          && other.c == c;
}
Run Code Online (Sandbox Code Playgroud)

话虽这么说,我发现了一个主要问题,被调用的 == 运算符似乎是比较左侧的运算符。也就是说,Base == Derived将调用 Base 的 == 比较,同时Derived == Base将调用 Derived 的 == 比较(以及随后的 Base 的)。这看起来确实有道理,但让我摸不着头脑。

前任:

main() {
    Base b = new Base();
    Derived d1 = new Derived();
    Derived d2 = new Derived();

    b.a = 6;
    d1.a = 6;
    d2.a = 6;

    b.b = "Hi";
    d1.b = "Hi";
    d2.b = "Hi";

    d1.c = 1;
    d2.c = 1;

    assert(d1 == d2); // pass
    assert(b == d1);  // PASS!!!
    assert(d1 == b);  // fail
}
Run Code Online (Sandbox Code Playgroud)

(注意:出于演示目的,我从字段中删除了私有 _。)