2010-08-05 17 views

回答

8

在VB.net:

if i > 0 then 
    do stuff here! 
end if 

在C#:

if (i > 0) 
{ 
    do stuff here! 
} 

你不能在if語句的 '突破'。如果你試圖這樣做,你的邏輯是錯誤的,並且你從錯誤的角度接近它。

你試圖達到的一個例子將有助於澄清,但我懷疑你是錯誤地構造它。

2

沒有這樣的等價,但你should't真的需要與if語句。您可能想要查看使用Select Case(VB)或Switch(C#)語句。

2

在C#.NET:

if (x > y) 
{ 
    if (x > z) 
    { 
     return; 
    } 

    Console.Writeline("cool"); 
} 

或者你可以使用goto聲明。

+1

你也可以拋出一個異常,並在'if'之外捕獲它。或者只是終止進程:) – RocketR 2011-07-16 20:34:17

+0

關於'goto'命令,請閱讀以下內容:http://stackoverflow.com/questions/46586/goto-still-considered-harmful – Gertsen 2016-02-18 15:19:15

-3

我知道這是一個老的文章,但我一直在尋找同樣的答案,然後最終我想通了

 try{ 

      if (i > 0) // the outer if condition 
      { 
       Console.WriteLine("Will work everytime"); 
       if (i == 10)//inner if condition.when its true it will break out of the outer if condition 
       { 
        throw new Exception(); 
       } 
       Console.WriteLine("Will only work when the inner if is not true"); 
      } 
     } 
     catch (Exception ex) 
     { 
      // you can add something if you want 
     } 

`

+7

使用異常控制流程的壞主意。他們很慢。 – 2011-11-07 14:04:35

+4

omg ...這是什麼瘋狂!?!? – 2012-01-20 21:29:21

+3

添加到@KateGregory所說的內容中,應該只在程序進入罕見,錯誤或意外狀態時使用異常。 對流量控制方式使用異常很難閱讀,易混淆,而且對其他人來說難以理解。 – Daryl 2012-04-26 19:47:00

0

您可以使用

bool result = false; 
if (i < 10) 
{ 
    if (i == 7) 
    { 
     result = true; 
     break; 
    } 
} 

return result; 
+0

代碼不能編譯,說明沒有循環可以跳出 – Breeze 2016-06-15 11:24:29