[英]C# equivalent to Java's continue <label>?
應該簡單快捷:我想要一個與以下Java代碼等效的C#:
orig: for(String a : foo) {
for (String b : bar) {
if (b.equals("buzz")) {
continue orig;
}
}
// other code comes here...
}
編輯 :好吧,似乎沒有這樣的等價物(嘿 - Jon Skeet自己說沒有,這就解決了;))。 所以我的“解決方案”(在其Java等價物中)是:
for(String a : foo) {
bool foundBuzz = false;
for (String b : bar) {
if (b.equals("buzz")) {
foundBuzz = true;
break;
}
}
if (foundBuzz) {
continue;
}
// other code comes here...
}
我不相信有一個等價的東西。 你必須要么使用布爾值,要么只是“轉到”外部循環內部的末端。 它甚至比聽起來更麻煩,因為標簽必須應用於聲明 - 但我們不想在這里做任何事情。 但是,我認為這可以滿足您的需求:
using System;
public class Test
{
static void Main()
{
for (int i=0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.WriteLine("i={0} j={1}", i, j);
if (j == i + 2)
{
goto end_of_loop;
}
}
Console.WriteLine("After inner loop");
end_of_loop: {}
}
}
}
不過,我強烈建議采用不同的表達方式。 我不能認為有很多次沒有更可讀的編碼方式。
其他可能性是使用內循環來實現一個功能:
void mainFunc(string[] foo, string[] bar)
{
foreach (string a in foo)
if (hasBuzz(bar))
continue;
// other code comes here...
}
bool hasBuzz(string[] bar)
{
foreach (string b in bar)
if (b.equals("buzz"))
return true;
return false;
}
在VB.Net中,您可以只有一個while
循環和一個for
循環,然后exit
所需的范圍級別。
在C#中,可能會break;
?
這可能會突破內循環並允許外循環繼續前進。
我認為你正在尋找簡單的“繼續”關鍵字...但是,不是一個Java人我真的沒有得到代碼片段試圖實現的東西。
但請考慮以下情況。
foreach(int i in new int[] {1,2,3,5,6,7})
{
if(i % 2 == 0)
continue;
else
Console.WriteLine(i.ToString());
}
第4行的continue語句是繼續循環下一個值的指令。 這里的輸出是1,3,5和7。
用“break”替換“continue”,如下所示,
foreach(int i in new int[] {1,2,3,5,6,7})
{
if(i % 2 == 0)
break;
else
Console.WriteLine(i.ToString());
}
將給出輸出1. Break指示循環終止,當您想要在滿足條件時停止處理時最常用。
我希望這能為您提供一些您想要的東西,但如果沒有,請隨時再詢問。
你可以這樣做:
for(int i=0; i< foo.Length -1 ; i++) {
for (int j=0; j< bar.Length -1; j++) {
if (condition) {
break;
}
if(j != bar.Length -1)
continue;
/*The rest of the code that will not run if the previous loop doesn't go all the way*/
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.