How can I use more than one constant for a switch case in C#?
How can I use more than one constant for a switch case C#? Conceptually, I'm looking for something like this:
switch(n)
{
case 1,2,3: //????
case 4:
default:
}
你不这样做,你会用掉落式的。
switch( n )
{
case x:
case y:
case z:
DoSomething( );
break;
case blah:
break;
}
A number of answers have stated that "fall through is legal if the case is empty".
This is not correct. This is the wrong way to think about it. This is reasoning as though C# were C, which it is not. In C, every case label has an associated statement list, possibly empty, and control 'falls through' off the end of the statement list. None of this is the case in C#.
In C#, a switch consists of a number of sections, each of which has one or more case labels, and each of which has one or more statements. When you say
switch(x)
{
case 1:
case 2:
M();
break;
}
It is NOT the situation that there are two switch sections, one for case 1 and one for case 2, and the switch section for case 1 is empty and falls through to the second block. That would be the situation in C, but C# is not C.
In C#, in this example there is ONE switch section. It has TWO labels, and ONE statement list. There is NOT an empty statement list between the case labels; there cannot be because the statement list follows the last label in the section. Let me repeat that: it is not the case that there is an empty statement list there. There is no statement list at all, not even an empty statement list.
This characterization allows us to clearly state the fall-through rule in C# which is "fall through is always illegal", period. Again, it is NOT the case that control "falls through" from the empty statement list of case 1 into case 2. Control never falls through. Control does not fall through here because control never enters the empty statement list after case 1. Control cannot enter that empty statement list because there isn't an empty statement list there in the first place. The statement list does not begin until after case 2.
C# enforces the no-fall-through rule in every switch section, including the last one. This is so that switch sections can be re-ordered arbitrarily, possibly by mechanical tools, without introducing semantic changes in the program.
C# enforces the no-fall-through rule by requiring that the end point of every switch section be unreachable. It is not necessary for a switch section to end in a break. It can end in a break, return, goto, continue, throw, or a detectable infinite loop:
switch(x)
{
case 1:
while(true) M();
case 2:
return 123;
case 3:
throw new Exception();
case 4:
M();
goto case 3;
}
All of the above are legal; there are no breaks.
switch(n)
{
case 1:
case 2:
case 3:
// do something
break;
default:
break;
}
链接地址: http://www.djcxy.com/p/84450.html
上一篇: 切换大小写,检查C#3.5中的范围
下一篇: 如何在C#中使用多于一个常量的开关情况?