我正在处理一个 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";
}
最佳答案
从 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";
}
关于c# - 在 Switch 语句中使用 .StartsWith?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952528/