是否可以从相同情况下的方法的开关情况中退出(返回)



是否可以从相同情况下的方法的开关情况中退出(返回(?

给定此代码:

switch(int blaah) {
case 1: 
some code here;
break;
case 2: 
myMethod();
some code here;
break;
default:
some code here;
}
public void myMethod() {
if(boolean condition) {
return;  
/*I want this return valuates in switch case too.
so the switch case exit without executing the rest of code of "case 2" */
}
some code here;
}

我知道这里的return只是跳过myMethod中的其余代码。我正在寻找告诉开关案例停止方法执行的东西。

如果没有完整的上下文,很难给出有意义的解决方案。

然而。。。

您可以从该方法返回一个布尔结果,基于此,开关情况可以决定是否继续。

public boolean myMethod() {
if(boolean condition) {
return false;
}
//some code here;
return true;
}

switch(int blaah) {
case 1: 
some code here;
break;
case 2: 
if (myMethod()) {
//some code here; //Execute only if the method signalled to do so
}
break;
default:
some code here;
}

另一种选择:

如果if(boolean condition)是您在该方法中做的第一件事,那么您可以在开关情况本身中对其进行评估,并且如果结果为true并立即中断,则可以避免调用该方法。

case 2: 
if (boolean condition) {
myMethod();
//some code here;
}
break;

最佳选择是

case 2: 
if (someCondition) {
myMethod();
}
else {
// some code
}
break;

最新更新