invalid_pattern_variable_in_shared_case_scope
變數 '{0}' 在所有共享此主體的 case 中沒有相同的型別和/或終結性。
變數 '{0}' 在共享此主體的一部分(但不是所有)case 中可用。
變數 '{0}' 不可用,因為存在標籤或 'default' case。
描述
#當 switch 語句中的多個 case 子句共享一個主體,並且其中至少一個聲明瞭在共享語句中引用的變數,但該變數未在所有 case 子句中宣告或以不一致的方式宣告時,分析器會生成此診斷。
如果該變數未在所有 case 子句中宣告,那麼如果匹配並執行主體的 case 子句之一是未宣告該變數的子句,則該變數將沒有值。這包括其中一個 case 子句是 default 子句的情況。
如果變數以不一致的方式宣告,例如在某些 case 中是 final 而在其他 case 中不是 final,或者在不同 case 中具有不同的型別,那麼該變數的型別或終結性的語義是未定義的。
示例
#以下程式碼會產生此診斷,因為變數 a 僅在一個 case 子句中宣告,如果第二個子句匹配了 x,則該變數將沒有值
void f(Object? x) {
switch (x) {
case int a when a > 0:
case 0:
a;
}
}以下程式碼會產生此診斷,因為變數 a 未在 default 子句中宣告,並且如果主體被執行(因為沒有其他子句匹配 x),則該變數將沒有值
void f(Object? x) {
switch (x) {
case int a when a > 0:
default:
a;
}
}以下程式碼會產生此診斷,因為如果主體被執行(因為另一組 case 導致控制流在標籤處繼續),則變數 a 將沒有值
void f(Object? x) {
switch (x) {
someLabel:
case int a when a > 0:
a;
case int b when b < 0:
continue someLabel;
}
}以下程式碼會產生此診斷,因為變數 a 雖然在所有 case 子句中都被賦值,但在每個子句中關聯的型別卻不相同
void f(Object? x) {
switch (x) {
case int a when a < 0:
case num a when a > 0:
a;
}
}以下程式碼會產生此診斷,因為變數 a 在第一個 case 子句中是 final,而在第二個 case 子句中不是 final
void f(Object? x) {
switch (x) {
case final int a when a < 0:
case int a when a > 0:
a;
}
}常見修復方法
#如果該變數未在所有 case 中宣告,並且您需要在語句中引用它,請在其他 case 中宣告它
void f(Object? x) {
switch (x) {
case int a when a > 0:
case int a when a == 0:
a;
}
}如果該變數未在所有 case 中宣告,並且您不需要在語句中引用它,請移除對它的引用並從其他 case 中移除宣告
void f(int x) {
switch (x) {
case > 0:
case 0:
}
}如果變數的型別不同,請確定變數應具有的型別並使 case 保持一致
void f(Object? x) {
switch (x) {
case num a when a < 0:
case num a when a > 0:
a;
}
}如果變數的終結性不同,請確定它應該是 final 還是非 final,並使 case 保持一致
void f(Object? x) {
switch (x) {
case final int a when a < 0:
case final int a when a > 0:
a;
}
}