Multiple cases in switch statement
Is there a way to fall through multiple case statements without stating case value:
repeatedly?
I know this works:
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;
}
but I'd like to do something like this:
switch (value)
{
case 1,2,3:
//Do Something
break;
case 4,5,6:
//Do Something
break;
default:
//Do the Default
break;
}
Is this syntax I'm thinking of from a different language, or am I missing something?
There is no syntax in C++ nor C# for the second method you mentioned.
There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.
I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:
switch (value)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
This syntax is from the Visual Basic Select...Case Statement:
Dim number As Integer = 8
Select Case number
Case 1 To 5
Debug.WriteLine("Between 1 and 5, inclusive")
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8
Debug.WriteLine("Between 6 and 8, inclusive")
Case Is < 1
Debug.WriteLine("Equal to 9 or 10")
Case Else
Debug.WriteLine("Not between 1 and 10, inclusive")
End Select
You cannot use this syntax in C#. Instead, you must use the syntax from your first example.
链接地址: http://www.djcxy.com/p/14778.html上一篇: 在switch语句中声明变量
下一篇: switch语句中有多个case