2016-01-21 112 views
0

。這是我的代碼:C#我如何逃生2線迴路

while(true){ 
    for(int x = 0; x < 10; x++){ 
     StringArray[x] = new string(); 
     if(isDead){ 
      break; //break out of while loop also 
     } 
    } 
} 

我應該怎麼做,請,對不起,如果我的英語不錯,我還在學習。

+1

你可以讓'X = 2',而不是'0',你應該提供何時打破循環的詳細信息? –

+5

[打破嵌套循環]可能的重複(http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop) – Houseman

+2

您可否提交所有的代碼,這不足以充分理解發生了什麼事。 –

回答

0

您可以創建例如布爾:

bool leaveLoop; 

如果isDead爲真,則設置leaveLoop爲true,while循環,然後檢查是否leaveLoop是真正從中折斷。

4

while循環更改爲一個變量,那麼該變量設置爲false(例如你的isDead變量)

while(!isDead){ 
    for(int x = 0; x < 10; x++){ 
     StringArray[x] = new string(); 
     if(isDead){ 
      break; //break out of while loop also 
     } 
    } 
} 

這樣,你break將帶你走出for循環,則具有isDead設置爲true將停止執行while循環。

0

如下嘗試:

bool bKeepRunning = true; 
while(bKeepRunning){ 
    for(int x = 0; x < 10; x++){ 
     StringArray[x] = new string(); 
     if(isDead){ 
     bKeepRunning = false; 
     break; 
    } 
    } 
} 
+1

這應該是有效的。 –

2

創建一個內聯函數,並調用它。使用lambda內的返回值。

var mt =() => { 
    while(true){ 
     for(int x = 0; x < 10; x++){ 
      StringArray[x] = new string(); 
      if(isDead){ 
       return 
      } 
     } 
    }  
} 
mt(); 
1

所以我理解你想打破2路的一個條件。你可以做以下

bool DirtyBool = true; 
while(DirtyBool) 
{ 
    for(int x = 0; x < 10; x++) 
    { 
     StringArray[x] = new string(); 
     if(isDead) 
     { 
      DirtyBool = false; 
      break; //break out of while loop also 
     } 
    } 
} 
0

我最喜歡的方式來這種情況是將代碼移動到一個單獨的程序,並簡單地從它返回時,我需要打破。無論如何,兩個循環的複雜程度與我想要包含在單個程序中一樣複雜。

0

您可以使用goto

while(true){ 
     for(int x = 0; x < 10; x++){ 
      StringArray[x] = new string(); 
      if(isDead){ 
       goto EndOfWhile; //break out of while loop also 
      } 
     } 
    } 
EndOfWhile: (continue your code here)