C#在两个数字之间切换?

时间:2015-07-27 19:21:13

标签: c# switch-statement

我正在尝试制作智能切换语句,而不是使用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"
}

它说案件不能互相落空。

感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

尝试使用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";

答案 1 :(得分:4)

根据最近的更改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 :(得分:1)

不,在开关案例中没有“范围”的语法。如果您不想列出个别案例而不是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";

我会使用没有写的人来阅读和理解最容易的。