Switch case:我可以使用一个范围而不是一个数字吗 [英] Switch case: can I use a range instead of a one number

查看:24
本文介绍了Switch case:我可以使用一个范围而不是一个数字吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用switch,但是我有很多情况,有什么捷径吗?到目前为止,我知道并尝试过的唯一解决方案是:

I want to use switch, but I have many cases, is there any shortcut? So far the only solution I know and tried is:

switch (number)
{
case 1: something; break;
case 2: other thing; break;
...
case 9: .........; break;
}

我希望我能做的是:

switch (number)
{
case (1 to 4): do the same for all of them; break;
case (5 to 9): again, same thing for these numbers; break;
}

推荐答案

这个问题有点晚了,但最近发生了变化 在 C# 7 中引入(在 Visual Studio 2017/.NET Framework 4.6.2 中默认可用),基于范围的切换是现在可以使用 switch 语句.

A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement.

示例:

int i = 63;

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

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

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

注意事项:

  • 括号 ()when 条件中不是必需的,但在此示例中用于突出显示比较.
  • var 也可以用来代替 int.例如:case var n when n >= 100:.
  • The parentheses ( and ) are not required in the when condition, but are used in this example to highlight the comparison(s).
  • var may also be used in lieu of int. For example: case var n when n >= 100:.

这篇关于Switch case:我可以使用一个范围而不是一个数字吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆