【问题标题】:How to add multi value in same case如何在相同的情况下添加多值
【发布时间】:2014-01-24 07:51:53
【问题描述】:

将多个值添加到同一案例时遇到问题:

这是我的 C# 代码

string input = combobox1.selectedvalue.ToString(); 
switch(input)
{
case "one";
     return 1;
     break;
case "two";
     return 2;
     break;
case "three" , "four":   // error here
     return 34;
     break;
default:
     return 0;
}

需要你的帮助

【问题讨论】:

    标签: c# switch-statement case multivalue


    【解决方案1】:

    只需使用单独的标签:

    string input = combobox1.selectedvalue.ToString(); 
    switch(input)
    {
    case "one":
         return 1;
         break;
    case "two":
         return 2;
         break;
    case "three": 
    case "four":
         return 34;
         break;
    default:
         return 0;
    }
    

    switch:

    每个 switch 部分包含一个或多个 case 标签,后跟一个或多个语句

    【讨论】:

    • 你甚至不需要breaks,因为你在每个开关部分都有一个return
    【解决方案2】:

    你可以在秋天,阅读this了解更多信息 所以它看起来像这样

    switch(input)
    {
    case "one":
         return 1;
         break;
    case "two":
         return 2;
         break;
    case "three":
    case "four": 
         return 34;
         break;
    default:
         return 0;
    }
    

    【讨论】:

    • fall through 传统上用于指示特定部分中的代码将运行,然后(在没有 break 的情况下)将继续到下一部分。确切地说,这不是 switch 在 C# 中的定义方式,并且不允许实际失败
    • 参见switch:“与其他一些语言不同,您的代码可能不会进入下一个切换部分”
    • 这段代码没有失败。它只是一个带有多个 case 标签switch 部分。所以 Damien 的 cmets 离题了。原始版本的唯一问题是案例标签末尾的;,而不是:
    • @CarstenHeine - 我的 cmets 特别指出,在这个答案中使用“fall through”这个短语是不正确的。
    【解决方案3】:

    正确的语法是

    case "three": 
    case "four":
         return 34;
         break;
    

    改为

    case "three" , "four": 
         return 34;
         break;
    

    来自switch (C# Reference)

    一个 switch 语句包含一个或多个 switch 部分。每个开关 部分包含一个或多个案例标签后跟一个或多个 声明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多