c# - C# - 如何从if语句中中断

我有这样的代码:


public void Method()


{


 if(something)


 {


 //some code


 if(something2)


 {


 now I should break from ifs and go to te code outside ifs


 }


 return;


 }


 // The code i want to go if the second if is true


}



我想知道,如果不使用goto语句或者其他代码,怎样可以在if之后转到其他代码。

时间:

使用else


if(something)


{


 //some code


 if(something2)


 {


 // now I should break from ifs and go to te code outside ifs


 }


 else return;


 }


 // The code i want to go if the second if is true



要回答你的问题:


public void Method()


{


 while(true){


 if(something)


 {


 //some code


 if(something2)


 {


 break;


 }


 return;


 }


 break;


 }


 // The code i want to go if the second if is true


}




public void Method()


{


 if(something)


 {


 //some code


 if(something2)


 {


 // now I should break from ifs and go to te code outside ifs


 goto done;


 }


 return;


 }


 // The code i want to go if the second if is true


 done: // etc.


}



相同问题

长答案

在这种情况下,插入单个else


public void Method()


{


 if(something)


 {


 // some code


 if(something2)


 {


 // now I should break from ifs and go to te code outside ifs


 }


 else return;


 }


 // The code i want to go if the second if is true


}



通常:if/else序列中没有break,只需正确排列你的代码,if / if else / else子句。


public void Method()


{


 if(something)


 {


 //some code


 if(!something2)


 {


 return;


 }


 }


 // The code i want to go if the second if is true


}




public void Method()


{


 if(something)


 {


 //some code


 if(something2)


 {


 // The code i want to go if the second if is true


 }


 return;


 }


}



只有在something2或者使用else return时,才能使用return :!


public void Method()


{


 if(something)


 {


 //some code


 if(something2)


 {


 //now I should break from ifs and go to te code outside ifs


 }


 if(!something2) // or else


 return;


 }


 // The code i want to go if the second if is true


}



尝试添加一个控制变量:


public void Method()


{


 bool doSomethingElse = true;


 if(something)


 {


 //some code


 if(!something2)


 {


 doSomethingElse = false;


 }


 }


 if(doSomethingElse)


 {


 // The code i want to go if the second if is true


 }


}



...