C# Switch If 条件来扩展 switch case

标签 c# if-statement switch-statement case

我有一些数据需要转换,为此我需要一个超过 50 个案例的切换条件,我需要 3 次相同的案例,但在第三次我需要 50 个案例和一些更多,我不想写两次相同的代码。也许有可能做这样的事情。

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    if (condition == true)
    {
        case "1":
            //do something else than above at case "1", and so on 
            //now its i little bit illogical, but i neet to do the first 50 cases and then
            //use the cases 1 to 50 again but with other actions 
    }
}

最佳答案

从 C# 7 开始,您可以组合 the case statement with when clause并使用它来稍微简化您的代码

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    case "51" when condition == true:
        //do something, and so on  
    default:
        break;   
}

Starting with C# 7.0, because case statements need not be mutually exclusive, you can add a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value.

关于C# Switch If 条件来扩展 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316019/

相关文章:

Java if 语句作业

java - 模式匹配开关是否需要在 Java 中始终详尽无遗?

java - 从外部类切换 Java 中的 jPanel

c# - 连接 C# 和 Java 的最佳方式是什么?

c# - 在 Silverlight 中检查互联网连接

Python:在可能存在或不存在的参数上使用 if 语句

检查 char 变量的内容 - C 编程

batch-file - 如何使用BATCH文件中的SWITCH解析命令行参数

c# - 使用 C# P/Invoke 的方法对 Struct 内的数组进行编码

javascript - C# 字符串到 Javascript var