6

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;
  }
}

次に、フィールドを追加し、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;
  }
}

私ができることは次のとおりです。

  • 派生クラスでも基本クラスのすべてのフィールドを比較します。基本クラスが変更された場合、非常にエラーが発生しやすく、基本と派生が異なるパッケージにある場合にも機能しません。
  • equals現在と同じロジックを持つ関数を宣言operator ==し、呼び出しsuper.equals()て基本クラスを比較し、すべての呼び出しを関数に委譲しoperator==ますequalsequalsただし、 andを実装するのはあまり魅力的ではないようoperator ==です。

では、この問題に対する最善の解決策または推奨される解決策は何ですか?

4

3 に答える 3

9

わかりました、さらにいくつかの実験の後、私は自分でそれを理解しました. それは単に呼び出すだけです:

super==(other)

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;
  }
于 2013-10-20T14:21:29.000 に答える