Amr*_*Amr 2 c# foreach continue keyword while-loop
在下面的C#代码片段中,
我在while循环中有一个' foreach'循环,我希望在foreach某个条件发生时跳转到' '中的下一个项目.
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
this.ExecuteSomeCode();
while (this.boolValue)
{
// 'continue' would jump to here.
this.ExecuteSomeMoreCode();
if (this.MoveToNextObject())
{
// What should go here to jump to next object.
}
this.ExecuteEvenMoreCode();
this.boolValue = this.ResumeWhileLoop();
}
this.ExecuteSomeOtherCode();
}
Run Code Online (Sandbox Code Playgroud)
' continue'会跳到' while'循环的开头而不是' foreach'循环.这里有一个关键字,或者我应该使用我不喜欢的goto.
使用break关键字.这将退出while循环并继续在其外执行.由于你之后没有任何东西,它会循环到foreach循环中的下一个项目.
实际上,更仔细地看一下你的例子,你实际上希望能够在不退出的情况下推进for循环.你不能用foreach循环来做这个,但你可以将foreach循环分解为实际自动化的循环.在.NET中,foreach循环实际上呈现为IEnumerable对象(this.ObjectNames对象所在)上的.GetEnumerator()调用.
foreach循环基本上是这样的:
IEnumerator enumerator = this.ObjectNames.GetEnumerator();
while (enumerator.MoveNext())
{
string objectName = (string)enumerator.Value;
// your code inside the foreach loop would be here
}
Run Code Online (Sandbox Code Playgroud)
拥有此结构后,可以在while循环中调用enumerator.MoveNext()以前进到下一个元素.所以你的代码将成为:
IEnumerator enumerator = this.ObjectNames.GetEnumerator();
while (enumerator.MoveNext())
{
while (this.ResumeWhileLoop())
{
if (this.MoveToNextObject())
{
// advance the loop
if (!enumerator.MoveNext())
// if false, there are no more items, so exit
return;
}
// do your stuff
}
}
Run Code Online (Sandbox Code Playgroud)