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