C# Switch Between Two Numbers?

♀尐吖头ヾ 提交于 2019-12-22 11:33:19

问题


I am trying to make an intelligent switch statement instead of using 20+ if statements. I tried this

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

It says cases cannot fall through each other.

Thanks for any help!


回答1:


Your syntax for trying to do a range with switch/case is wrong.

case 1 - 10: will be translated to case -9:

There are two ways you can attempt to cover ranges (multiple values):

List the cases individually

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";

Calculate a range

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

HOWEVER

You really should consider covering ranges of values with an if statement

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



回答2:


With recent changes introduced in C# 7, it is now possible to switch on a range.

Example:

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

Note: This really doesn't help the OP much, but hopefully it will help someone looking for this in the future.




回答3:


No, there's no syntax for a "range" within a switch case. If you don't want to list individual cases than an if/else will be cleaner:

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

which can also be shortened with the conditional operator:

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

I would use whichever is easiest to read and understand by someone who didn't write it.



来源:https://stackoverflow.com/questions/31661515/c-sharp-switch-between-two-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!