C#中如何用switch对非常量字符串值执行模式匹配?
问题原因
标准C#传统switch语句的case标签要求必须传入编译时常量,你定义的expectedValue是运行时变量,不符合语法要求,因此触发CS0150: 应为常量值报错。
可行解决方案
方案1:使用带模式匹配的switch语句(C# 7.0+支持,兼容性最好)
直接在case后加when条件匹配非常量值,修改后的代码如下:
public bool UseStandardSwitch(string inputValue) { var expectedValue = "SomeValue"; bool result = default; var DoSomething = () => { result = true; }; switch (inputValue) { // 用模式匹配加when条件匹配非常量变量 case string s when s == expectedValue: DoSomething(); break; default: break; } return result; }
如果需要匹配多个非常量值,只要追加对应case string s when s == xxx:分支即可。
方案2:使用switch表达式(C# 8.0+支持,写法更简洁)
如果你的项目支持更高版本C#,可以用更精简的switch表达式实现相同逻辑:
public bool UseStandardSwitch(string inputValue) { var expectedValue = "SomeValue"; return inputValue switch { string s when s == expectedValue => true, _ => default }; }
方案3:直接用if判断(兼容性最高,所有版本C#都支持)
如果逻辑分支不多,也可以直接用if判断替代switch,不需要依赖高版本C#特性:
public bool UseStandardSwitch(string inputValue) { var expectedValue = "SomeValue"; return inputValue == expectedValue; }
内容的提问来源于stack exchange,提问作者derekbaker783
相关产品推荐
相关产品推荐

