【问题标题】:C# Switch If condition to expand the switch casesC# Switch If 条件来扩展 switch 案例
【发布时间】:2020-02-20 08:51:25
【问题描述】:

我有一些需要转换的数据,因为我需要一个超过 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 
    }
}

【问题讨论】:

  • 你的问题不清楚,你在找什么?
  • 那么,在case "50" 你也想检查case "51" 等等?
  • 你可以试试goto语句,虽然不推荐
  • 你对 1-50(条件 == false)和条件为 true 的 1-50 的操作是什么样的?

标签: c# if-statement switch-statement case


【解决方案1】:

从 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;   
}

从 C# 7.0 开始,因为 case 语句不需要相互 独占,您可以添加一个when 子句来指定一个额外的 case 语句评估为必须满足的条件 真的。 when 子句可以是任何返回 Boolean 的表达式 价值。

【讨论】:

  • 这很好,但在我需要的更多情况下,有些情况需要两次,如 case "0":如果我使用 when 子句这样做,它就不起作用。
  • @Luuke 不完全清楚,这里两次是什么意思。请使用这些详细信息更新您的问题。要在case 语句之间转移控制,您可以使用goto 语句
  • @Luuke 如果您需要通过不同的操作再次使用这些案例,这看起来就像编写一个新案例并将它们放在一个单独的方法中。或者将所有操作放在同一个case 下,并使用when 子句进行控制。你能分享一下动作的例子吗?为什么需要用不同的动作重复相同的案例?
【解决方案2】:

我想您正在寻找一种不重复 if (condition == true) 的方法。除了 C#7 中的新 when 子句之外,您还可以使用两个 switch 语句采取不同的方法:

if (!condition)
{
    switch (example)
    {
        case "1":
            //do something
        case "2":
            //do something
        case "50":
            //do something
    }
} else {
    switch (example)
    {
        case "51:
            //do something, and so on 
    }
}

【讨论】:

    【解决方案3】:

    使用条件的with 创建一个始终匹配的案例。

    switch (example)
    {
        case "1":
        case example when condition == true:
            //do something
        case "2":
            //do something
        case "50":
            //do something
    }
    

    【讨论】:

    • 虽然此代码可能会为 OP 的问题提供解决方案,但强烈建议您提供有关此代码为何和/或如何回答问题的额外上下文。从长远来看,只有代码的答案通常会变得毫无用处,因为未来遇到类似问题的观众无法理解解决方案背后的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多