跳到主要內容

relational_pattern_operand_type_not_assignable

常量表達式型別“{0}”無法賦值給“{2}”運算子的引數型別“{1}”。

描述

#

當關系模式的運算元型別無法賦值給將被呼叫的運算子的引數型別時,分析器會生成此診斷資訊。

示例

#

以下程式碼會產生此診斷資訊,因為關係模式中的運算元 (0) 是 int 型別,但類 C 中定義的 > 運算子需要 C 型別的物件。

dart
class C {
  const C();

  bool operator >(C other) => true;
}

void f(C c) {
  switch (c) {
    case > 0:
      print('positive');
  }
}

常見修復方法

#

如果 switch 正在使用正確的值,則更改 case 以將該值與正確型別的物件進行比較。

dart
class C {
  const C();

  bool operator >(C other) => true;
}

void f(C c) {
  switch (c) {
    case > const C():
      print('positive');
  }
}

如果 switch 正在使用錯誤的值,則更改用於計算匹配值的表示式。

dart
class C {
  const C();

  bool operator >(C other) => true;

  int get toInt => 0;
}

void f(C c) {
  switch (c.toInt) {
    case > 0:
      print('positive');
  }
}