c# - 在 Switch 语句中使用 .StartsWith?

标签 c# asp.net .net

我正在处理一个 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/

相关文章:

c# - 多个窗口导航相同的数据集合

asp.net - ASP :QueryStringParameter and empty query string parameter

c# - 如何使用System.DirectoryServices.Protocols更改密码

c# - 如何写方法描述

c# - 是否可以使用 MEF RegistrationBuilder 创建 PRISM ModuleExport?

c# - 由字段初始化引起的有害代码爆炸的真实示例是什么?

c# - Linq 无法隐式转换类型

c# - 使用dapper访问Mysql

c# - 为什么为空(登录弹出窗口)

c# - cshtml中 '@'标志是什么意思?