跳到主要內容

case_expression_type_implements_equals

switch case 表示式型別 '{0}' 不能覆寫 '==' 運算子。

描述

#

當跟在關鍵字 case 後面的表示式型別實現了 == 運算子,但不是 Object 中實現的那個時,分析器會產生此診斷。

示例

#

以下程式碼會產生此診斷,因為跟在關鍵字 case 後面的表示式 (C(0)) 的型別是 C,而類 C 覆寫了 == 運算子

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  switch (c) {
    case C(0):
      break;
  }
}

常見修復方法

#

如果沒有強烈的理由不這樣做,則將程式碼重寫為使用 if-else 結構

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  if (c == C(0)) {
    // ...
  }
}

如果你無法重寫 switch 語句且不需要 == 的實現,則將其刪除

dart
class C {
  final int value;

  const C(this.value);
}

void f(C c) {
  switch (c) {
    case C(0):
      break;
  }
}

如果你無法重寫 switch 語句且無法刪除 == 的定義,則找到一些其他可用於控制 switch 的值

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  switch (c.value) {
    case 0:
      break;
  }
}