我想知道是否可以提前退出函数,绕过正文中的其余代码.例如:
public class SOMECLASS {
public SOMECLASS( int i ) {
gotoSwitchCase(i);
additionalTask(); // method body is irrelevant
}
private void gotoSwitchCase(int i) {
switch (i) {
case 0:
/* exit ctor prematurely */
break;
default:
/* set some instance variables, return to ctor */
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以if(i==0){return;}在开始时插入additionalTask()以跳过该部分.但是,我更感兴趣的是,是否有一种方法可以优雅地退出构造函数(或任何函数)而无需访问其余部分.类似于例外,但不是致命的.
如果您希望提前退出函数(包括构造函数),只需使用该return;命令即可.这也适用于构造函数.
编辑以澄清:这是解决此问题的正确方法.您不能跳过从主体中跳过构造函数的其余部分,gotoSwitchCase因为gotoSwitchCase可以从构造函数或其可见的任何其他方法运行.
| 归档时间: |
|
| 查看次数: |
3504 次 |
| 最近记录: |