可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a switch statement such as the one below:
switch (condition)
{
case 0:
case 1:
// Do Something
break;
case 2:
// Do Something
case 3:
// Do Something
break;
}
I get a compile error telling me that Control cannot fall through from one case label ('case 2:') to another
Well... Yes you can. Because you are doing it from case 0:
through to case 1:
.
And in fact if I remove my case 2:
and it's associated task, the code compiles and will fall through from case 0:
into case1:
.
So what is happening here and how can I get my case statements to fall through AND execute some intermediate code?
回答1:
There is a difference between stacking labels and fall-through.
C# supports the former:
case 0:
case 1:
break;
but not fall-through:
case 2:
// Do Something
case 3:
// Do Something
break;
If you want fall-through, you need to be explicit:
case 2:
// Do Something
goto case 3;
case 3:
// Do Something
break;
The reasoning is apparent, implicit fall-through can lead to unclean code, especially if you have more than one or two lines, and it isn't clear how the control flows anymore. By forcing the explicit fall-through, you can easily follow the flow.
Reference: msdn
回答2:
Quoting MSDN:
"C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code."
basically it is not legal to put statements inside the case and not include a break.
case 1:
case 2:
//do stuff
break;
is legal
but:
case 1:
//do stuff without a break
case 2:
//do stuff
break;
is not.
http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.80).aspx
回答3:
You are not falling from case 0
to case 1
since they share the same code block. This is the same as writing case 1
before case 0
.
回答4:
In C#, you cannot fall through a label to another implicitly except if there is no specific code for the first label.
You can have
case 1:
case 2:
// Do Something
break;
but not
case 1:
// Do Something
case 2:
// Do Something
break;
See msdn for a more in-depth explanation.
If you wish to fall through explicitly, you can by using the goto instruction. It is also one of the rare case where using goto isn't a bad practice.
case 1:
// Do Something
goto case 2;
case 2:
// Do Something
break;
回答5:
Code can "fall through" in C# only when there is no code between the case statements. The code example infers there is code between case 2 and case 3.
回答6:
This is not allowed
switch (condition)
{
case 0:
// Do Something
case 1:
// Do Something
break;
}
This is allowed
switch (condition)
{
case 0:
case 1:
// Do Something
break;
}
回答7:
The problem is that you're doing something in case 2 and then trying to fall through, and that's not supported. You're going from 0 to 1 without any additionaly activity.