You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:06:02