这就是我想要做的事情:
switch(myvar)
{
case: 2 or 5:
...
break;
case: 7 or 12:
...
break;
...
}
我试过“case:2 || 5”,但它没有用。
目的是不为不同的值编写相同的代码。
答案 0 :(得分:288)
通过堆叠每个开关盒,您可以实现OR条件。
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
答案 1 :(得分:34)
您可以通过stacking case labels:
来完成switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
答案 2 :(得分:19)
case 2:
case 5:
do something
break;
答案 3 :(得分:17)
案例陈述会自动落空。因此你可以写
switch(myvar)
{
case 2:
case 5:
{
//your code
break;
}
//等...... }
答案 4 :(得分:4)
switch statement的示例显示您无法堆叠非空case
,但应使用goto
s:
// statements_switch.cs
using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or3.");
break;
}
if (cost != 0)
Console.WriteLine("Please insert {0} cents.", cost);
Console.WriteLine("Thank you for your business.");
}
}
答案 5 :(得分:1)
func createYearDictionary(students: [Student]) -> [Int: [String]] {
var result = [Int: [String]]()
for student in students {
if result[student.yearOfGraduation] == nil {
result[student.yearOfGraduation] = [student.name]
} else {
result[student.yearOfGraduation]?.append(student.name)
}
}
return result
}