是否有一种方法可以通过多个case语句而不声明case值:重复?
我知道这很管用:
switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
但我想这样做:
switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
这是我从另一种语言中想到的语法,还是我遗漏了什么?
如果你有非常大量的字符串(或任何其他类型)的情况下都做同样的事情,我建议使用字符串列表结合字符串。包含属性。
如果你有一个大的switch语句
switch (stringValue)
{
case "cat":
case "dog":
case "string3":
...
case "+1000 more string": // Too many string to write a case for all!
// Do something;
case "a lonely case"
// Do something else;
.
.
.
}
你可能想用这样的if语句替换它:
// Define all the similar "case" string in a List
List<string> listString = new List<string>(){ "cat", "dog", "string3", "+1000 more string"};
// Use string.Contains to find what you are looking for
if (listString.Contains(stringValue))
{
// Do something;
}
else
{
// Then go back to a switch statement inside the else for the remaining cases if you really need to
}
这适用于任意数量的字符串情况。
c# 7的原始答案
在c# 7中(默认在Visual Studio 2017中可用)。NET Framework 4.6.2),基于范围的切换现在可以通过switch语句实现,这将有助于解决OP的问题。
例子:
int i = 5;
switch (i)
{
case int n when (n >= 7):
Console.WriteLine($"I am 7 or above: {n}");
break;
case int n when (n >= 4 && n <= 6 ):
Console.WriteLine($"I am between 4 and 6: {n}");
break;
case int n when (n <= 3):
Console.WriteLine($"I am 3 or less: {n}");
break;
}
// Output: I am between 4 and 6: 5
注:
括号(和)在when条件中不是必需的,但在本例中用于突出显示比较。
Var也可以用来代替int。例如:case var n when n >= 7:。
c# 9的更新示例
switch(myValue)
{
case <= 0:
Console.WriteLine("Less than or equal to 0");
break;
case > 0 and <= 10:
Console.WriteLine("More than 0 but less than or equal to 10");
break;
default:
Console.WriteLine("More than 10");
break;
}
or
var message = myValue switch
{
<= 0 => "Less than or equal to 0",
> 0 and <= 10 => "More than 0 but less than or equal to 10",
_ => "More than 10"
};
Console.WriteLine(message);
如果你有非常大量的字符串(或任何其他类型)的情况下都做同样的事情,我建议使用字符串列表结合字符串。包含属性。
如果你有一个大的switch语句
switch (stringValue)
{
case "cat":
case "dog":
case "string3":
...
case "+1000 more string": // Too many string to write a case for all!
// Do something;
case "a lonely case"
// Do something else;
.
.
.
}
你可能想用这样的if语句替换它:
// Define all the similar "case" string in a List
List<string> listString = new List<string>(){ "cat", "dog", "string3", "+1000 more string"};
// Use string.Contains to find what you are looking for
if (listString.Contains(stringValue))
{
// Do something;
}
else
{
// Then go back to a switch statement inside the else for the remaining cases if you really need to
}
这适用于任意数量的字符串情况。