【发布时间】:2011-07-20 02:36:03
【问题描述】:
在 Java 中它是这样写的..当我移植这段代码时......意识到没有这样的东西
break <label> 和 continue <label>。
我知道这些命令不包括在内,因为在使用带有命令的 goto 时必须有一种更简洁的方法。
但我最终使用.. 下面的 C# 代码以任何方式重写它?
Java 代码
for(JClass c : classes) {
for(JMethod m : c.getMethods()) {
JCode code = m.getCode();
if(code == null)
continue;
label: for(int index = 0; index < code.getExceptionLookupTable().length; index++) {
JException e = code.getExceptionTable().get(index);
for(int index2 = e.getStartIndex(); index2 < e.getEndIndex(); index2++)
if(code.getInstruction(index2).getOpcode() == NEW && ((NEW) code.getInstruction(index2)).getType().equals("java/lang/RuntimeException"))
continue label;
if(e.getCatchTypeClassName().equals("java/lang/RuntimeException")) {
for(int index = e.getHandlerIndex(); index < code.getInstrLength(); index++) {
JInstruction instr = code.getInstruction(index);
if(instr.getOpcode() == ATHROW)
break;
else if(instr instanceof ReturnInstruction)
break label;
}
removeStuff(code, ei--);
}
}
}
}
C# 代码。
foreach(JClass c in classes) {
foreach(JMethod m in c.getMethods()) {
JCode code = m.getCode();
if(code == null)
continue;
for(int index = 0; index < code.getExceptionTable().Length; index++) {
bool continueELoop = false;
bool breakELoop = false;
JException e = code.getExceptionTable().get(index);
for(int index2 = e.getStartIndex(); index2 < e.getEndIndex(); index2++) {
if(code.getInstruction(index2).getOpcode() == JInstructions.NEW && ((NEW) code.getInstruction(index2)).getType().Equals("java/lang/RuntimeException")) {
continueELoop = true;
break;
}
}
if(continueELoop) continue;
if(e.getCatchTypeClassName().Equals("java/lang/RuntimeException")) {
for(int index = e.getHandlerIndex(); index < code.getInstrLength(); index++) {
JInstruction instr = code.getInstruction(index);
if (instr.getOpcode() == JInstructions.ATHROW) {
break;
} else if (isReturnInstruction(instr)) {
breakELoop = true;
break;
}
}
removeStuff(code, ei--);
}
if (breakELoop) break;
}
}
}
当查看 Java 版本然后查看移植的 C# 版本时,您会看到......干净的感觉消失了。我是否犯了一些可以使代码更短的错误?还是更好看?感谢您的帮助。
【问题讨论】:
-
也许我老了,但我会尝试不止一种方法。您可以利用返回表达式作为伪中断来标记。
-
break label与 GOTO 有何不同? -
不是,但 goto 看起来确实比仅使用布尔条件更糟。至少像这样我可以看到
continue <label>和break<label>之间的相似性。除非有办法使用 goto 执行continue label,否则我会更改它。 -
@Cameron: GOTO 允许任意跳转,
break label只能跳转到父块的标签,标签只能附加到块上。break label旨在使嵌套中断更容易一些。
标签: c# java label break continue