c# - 在C#中,如何使用switch对非常量字符串值进行模式匹配?

在C#中,如何使用switch对非常量字符串值进行模式匹配?

我希望能够使用非常量字符串变量作为 switch 语句中的匹配目标。

我有下面的代码,但我遇到错误 CS0150: A constant value is expected at case expectedValue:

public bool UseStandardSwitch(string inputValue)
{
    var expectedValue = "SomeValue";

    bool result = default;
    var DoSomething = () => { result = true; };
            
    switch (inputValue)
    {
        case expectedValue:
            DoSomething();
            break;
        default:
            break;
    }
    return result;
}

有没有办法达到类似的效果?

最佳答案

无需引入变量(如您的回答)- 您可以将 discard 与 case guard 结合使用:

public bool UseStandardSwitch(string inputValue)
{
    var expectedValue = Console.ReadLine()!;
    Func<bool> DoSomething = () => true;
    
    return inputValue switch
    {
        _ when inputValue.Equals(expectedValue) => DoSomething(),
        _ when inputValue.Equals(expectedValue + "1") => DoSomething(),
        _ => throw new ArgumentException(),
    };
}

https://stackoverflow.com/questions/70215555/

相关文章:

blockchain - 安全帽测试 : is not a funct

c - 为什么这个计算字符串长度的 C 程序会给出错误的输出?

gradle - 如何在 GitHub 工作流程中重用 gradle 缓存

java - 错误 :Kotlin: Module was compiled with an inc

c++ - 是否有标准的 Untokenize 模板化类型?

python - 如何在句子中交替替换单词中的大小写字母? Python

kotlin - 是否可以使用私有(private)辅助构造函数在 Kotlin 中分配一个 val

typescript - zod:将字符串转换为数字后设置最小最大值

bash - 在 bash 中的字母处剪切数字字符串

c# - 循环中 Enumerable Count 方法的性能