在Java中,它是這樣寫的。當我移植這個代碼時...意識到沒有這樣的東西,如 break <label>
和continue <label>
。如何在C#中重寫Java [繼續<label>並打破<label>]?
我知道這些命令不包括在內,因爲必須有使用帶有命令轉到當這樣做的更清潔的方式..
但最後我用下面..任何方式的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#版本時,你可以看到..乾淨的感覺消失。我是否犯了一些可以縮短代碼的錯誤?或更好看?謝謝您的幫助。
也許我老了,但我會打入更多比一種方法。比你可以利用返回表達式作爲僞中斷標籤。 –
'斷標籤'與GOTO有什麼不同? – Cameron
它不是,但goto的看起來更糟,然後只使用bool條件。至少我這樣看到'continue