[英]In a c# switch, can I use a case as default?
Can I refer to a case in default instead of copy-pasting the whole code? 我可以默认引用一个案例,而不是复制粘贴整个代码吗?
For example: 例如:
switch(n)
{
case(1): //code here...
break;
case(2): //code here...
break;
case(3): //code here...
break;
default: case(2);
break;
}
Just put it second to last, followed by default
: 只需倒数第二,
default
:
switch(n)
{
case(1): //code here...
break;
case(3): //code here...
break;
case(2):
default: //code here...
break;
}
Or simply, not include it at all. 或者简单地,根本不包括它。 If that case isn't hit, then it will fall back to the default anyway.
如果没有遇到这种情况,那么无论如何它将恢复为默认值。
You can do like this. 你可以这样 If there is no case, it will got to the
default
. 如果没有,它将恢复为
default
。
switch(n)
{
case(1): //code here...
break;
case(3): //code here...
break;
default:
break;
}
No need to do 没必要做
case(2):
default: //code here...
break;
If you want to refer default to case 2, you can omit case 2. Then every case 2 should jump to case default. 如果要将默认值引用到案例2,则可以省略案例2。然后,每个案例2都应跳转到案例默认值。
switch(n)
{
case(1): //code here...
break;
case(3): //code here...
break;
default: //case 2 should jump to this section because its not listed in your switch-cases
break;
}
If you don't have any code in the default
case, you can simply omit case 2 and move that code to the default, like the other answers say. 如果
default
情况下没有任何代码,则可以简单地忽略情况2并将该代码移至默认情况,就像其他答案所说的那样。
If you do have code that has to be run in the default
case before you want to move on to case 2, you can use a goto
. 如果您确实有要在
default
情况下运行的代码,然后再继续进行情况2,则可以使用goto
。 Here's an example using int
: 这是使用
int
的示例:
int n = 5;
switch(n)
{
case 1: //code here...
break;
case 2: //code here...
break;
case 3: //code here...
break;
default:
//some code
goto case 2;
}
Something like this: 像这样:
switch(n)
{
case(1): //code here...
break;
case(3): //code here...
break;
case(2):
default:
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.