更新:
有没有办法完成下面的代码尝试做的事情(不通过语法,因为案例2和案例3不能有重复的声明和/或因为num不能同时为2和3 )?
var num = 0;
switch (num)
{
case 1:
//do stuff applicable to 1 only;
break;
case 2:
//do stuff applicable to 2 only;
break;
case 3:
//do stuff applicable to 3 only;
break;
case 2:
case 3:
//do stuff applicable to 2 and 3 only;
break;
}
答案 0 :(得分:6)
这个问题令人困惑。我认为你想要的是一个运行两个的案例,一个运行三个的案例,一个运行两个或三个的案例。
只需使用两个开关:
switch (num)
{
case 1: One(); break;
case 2: Two(); break;
case 3: Three(); break;
}
switch (num)
{
case 2:
case 3: TwoOrThree(); break;
}
或者
switch (num)
{
case 1: One(); break;
case 2:
case 3:
switch (num)
{
case 2: Two(); break;
case 3: Three(); break;
}
TwoOrThree();
break;
}
或复制代码:
switch (num)
{
case 1: One(); break;
case 2: Two(); TwoOrThree(); break;
case 3: Three(); TwoOrThree(); break;
}
我不建议像这样重复代码:
switch (num)
{
case 1: One(); break;
case 2: Two(); goto twoOrThree; break;
case 3: Three(); twoOrThree: TwoOrThree(); break;
}
呸。
答案 1 :(得分:2)
不是单级switch
(或令人讨厌的GOTO)。一个开关只能执行一个案例。在2/3案例中,更好的解决方案是嵌套if
(或switch
):
switch (num)
{
case 1:
//do stuff applicable to 1 only
break;
case 2:
case 3:
if(num == 2)
{
//do stuff applicable to 2 only
}
if(num == 3)
{
//do stuff applicable to 3 only
}
//do stuff applicable to 2 OR 3
break;
}
答案 2 :(得分:1)
就这么简单......
switch (value)
{
case 1:
// Do 1 stuff
break;
case 2:
case 3:
// We can use an if-else construct here given that there's only two possibilities.
if (value == 2)
{
// 2 only stuff here
}
else
{
// 3 only stuff here
}
// Do anything applicable to BOTH here, or above the if construct, depending on your requirements.
break;
default:
// Any other stuff here
break;
}
或者只使用if构造,它可以说更清晰(切换实际上仅用于简单的多对一逻辑映射)...
if (value == 1)
{
// 1 stuff
}
else if (value == 2 || value == 3)
{
if (value == 2) {
// 2 stuff only
}
else
{
// 3 stuff only
}
// 2 or 3 stuff, or above the if construct above, if you require.
}
else
{
// Anything else here
}
或者只是......
switch (value)
{
case 1:
OneStuff();
break;
case 2:
TwoStuff();
TwoOrThreeStuff();
break;
case 3:
ThreeStuff();
TwoOrThreeStuff();
break;
default:
AnythingElse();
}
用不同的方法包装你需要做的每件事。
第三种方法是我的偏好。它比使用开关的复杂混合物更简洁,更容易调试。
答案 3 :(得分:0)
您只能使用if
语句
var num = 0;
if(num == 1)
{
// do stuff applicable to 1 only
}
else if(num == 2)
{
// do stuff applicable to 2 only
}
else if(num == 3)
{
// do stuff applicable to 3 only
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}
或switch
和if
switch (num)
{
case 1:
// do stuff applicable to 1 only
break;
case 2:
// do stuff applicable to 2 only
break;
case 3:
// do stuff applicable to 3 only
break;
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}
答案 4 :(得分:-1)
您可以使用goto case语句,并在案例2和3中为组合操作设置唯一标识符。请确保它永远不会被任何其他数字命中:
var num = 0;
var text = "";
switch (num)
{
case 1:
text = "do stuff applicable to 1 only";
break;
case 2:
text = "do stuff applicable to 2 only";
goto case 23;
case 3:
text = "do stuff applicable to 3 only";
goto case 23;
case 23:
text = "do stuff applicable to 2 AND 3";
break;
}
一般不建议使用goto,但通常在switch语句和类似的情况下使用它。