我正在处理一个Switch语句,并且有两个条件我需要查看值是否以特定值开头.Switch语句是这样的.错误说"不能将bool类型转换为字符串".
任何人都知道我是否可以在Switch中使用StartsWith或者我是否需要使用If ... Else语句?
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
case subArea.StartsWith("3*"):
case subArea.StartsWith("03*"):
return "123";
default:
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
小智 23
从 C# 9 开始,您可以执行以下操作:
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
case { } when subArea.StartsWith("3*"):
case { } when subArea.StartsWith("03*"):
return "123";
default:
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
小智 20
从 C# 7 开始,您可以执行以下操作:
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
case string s when s.StartsWith("3*"):
return "123";
case string s when s.StartsWith("03*"):
return "123";
default:
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
Bhu*_*Bhu 16
感谢when 子句,您现在可以执行以下操作:
switch (subArea)
{
// Skipping regular cases with string literals
case string dummy
when subArea.StartsWith("3*") ||
subArea.StartsWith("03*"):
return "123";
default:
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
app*_*yip 13
你正在切换一个String
,并subArea.StartsWith()
返回一个Boolean
,这就是为什么你不能这样做.我建议你这样做:
if (subArea.StartsWith("3*") || subArea.StartsWith("03*"))
return "123";
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
default:
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
结果将是相同的.
小智 8
从 C# 9 开始,您还可以使用 switch 表达式而不是语句执行类似的操作:
return subArea switch
{
"4100" or "4101" or "4102" or "4200" => "ABC",
"600A" => "XWZ",
{ } when subArea.StartsWith("3*") || subArea.StartsWith("03*") => "123",
_ => "ABCXYZ123"
};
Run Code Online (Sandbox Code Playgroud)
案例标签必须是字符串,因为switch表达式是一个字符串。但是,StartsWith
返回一个布尔值。我建议在本default
节中处理这些特殊情况。
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
default:
if (subArea.StartsWith("3") || subArea.StartsWith("03")) {
return "123";
}
return "ABCXYZ123";
}
Run Code Online (Sandbox Code Playgroud)
除非您想subArea
包含星号(*),否则它可能是错误的。StartWith
不接受通配符。
另外,您可以使用正则表达式:
if (Regex.IsMatch(subArea, "^3|^03")) { // or "^(3|03)"
return "123";
}
Run Code Online (Sandbox Code Playgroud)
其中^
装置开始线和|
手段或。
归档时间: |
|
查看次数: |
10780 次 |
最近记录: |