【问题标题】:C# Switch Between Two Numbers?C# 在两个数字之间切换?
【发布时间】:2015-10-18 03:15:34
【问题描述】:

我正在尝试制作一个智能 switch 语句,而不是使用 20 多个 if 语句。我试过这个

private int num;
switch(num)
{
    case 1-10:
        Return "number is 1 through 10"
        break;
    default:
        Return "number is not 1 through 10"
}

它说案件不能互相失败。

感谢您的帮助!

【问题讨论】:

  • 为什么不使用单个 if/else 块,其条件类似于 if (num >= 1 && num <= 10)
  • 相关(如果不重复):stackoverflow.com/a/13927939/961113
  • 我建议使用您面前的工具,例如Google C# switch case statement syntax 代码的方法签名属于 Retun 是一个关键字并且是小写的

标签: c# switch-statement


【解决方案1】:

随着最近introduced in C# 7 的更改,现在可以在一个范围内使用switch

示例:

int i = 63;

switch (i)
{
    case int n when (n >= 10):
    Console.WriteLine($"I am 10 or above: {n}");
    break;

    case int n when (n < 10 && n >= 5 ):
    Console.WriteLine($"I am between 10 and 5: {n}");
    break;

    case int n when (n < 5):
    Console.WriteLine($"I am less than 5: {n}");
    break;
}

注意:这对 OP 确实没有多大帮助,但希望它能帮助将来寻找此功能的人。

【讨论】:

    【解决方案2】:

    您尝试使用 switch/case 进行范围的语法是错误的。

    case 1 - 10: 将被翻译成case -9:

    有两种方法可以尝试覆盖范围(多个值):

    单独列出案例

    case 1: case 2: case 3: case 4: case 5:
    case 6: case 7: case 8: case 9: case 10:
        return "Number is 1 through 10";
    default:
        return "Number is not 1 though 10";
    

    计算范围

    int range = (number - 1) / 10;
    switch (range)
    {
        case 0: // 1 - 10
            return "Number is 1 through 10";
        default:
            return "Number is not 1 though 10";
    }
    

    但是

    您确实应该考虑使用 if 语句覆盖值范围

    if (1 <= number && number <= 10)
        return "Number is 1 through 10";
    else
        return "Number is not 1 through 10";
    

    【讨论】:

      【解决方案3】:

      不,switch case 中没有“范围”的语法。如果您不想列出个别案例,那么 if/else 会更简洁:

      if(num >= 1 && num <= 10)
          Return "number is 1 through 10";
      else    
          Return "number is not 1 through 10";
      

      也可以用条件运算符缩短:

      return (num >= 1 && num <= 10)
          ? "number is 1 through 10"
          : "number is not 1 through 10";
      

      我会使用最容易被非编写者阅读和理解的那个。

      【讨论】:

        【解决方案4】:

        我知道我参加聚会很晚了,但如果有人想知道现在是如何做到的,那么请看一下这个例子:

        public string IsBetween1And10(int num)
        {
            return num switch
            {       
                >= 1 and <= 10 => "number is 1 through 10",
                _ => "number is not 1 through 10"
            };
        }
        

        【讨论】:

          猜你喜欢
          • 2016-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多