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

C# Switch Between Two Numbers?(C# 在两个数字之间切换?)

本文介绍了C# 在两个数字之间切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个智能 switch 语句,而不是使用 20 多个 if 语句.我试过这个

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.

感谢您的帮助!

推荐答案

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

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

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

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

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

单独列出案例

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

这篇关于C# 在两个数字之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 在两个数字之间切换?