C#相当于Java的继续?

应该简单快捷:我想要一个与以下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*/ } }