在 foreach 内继续
在以下 C# 代码片段中
我在“foreach
”循环内有一个“while
”循环,并且我希望在某个特定时刻跳转到“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();
}
“continue
”将跳转到“while
”循环的开头,而不是“foreach
”循环的开头。 这里是否需要使用关键字,或者我应该使用我不太喜欢的 goto 。
In the following C# code snippet
I have a 'while
' loop inside a 'foreach
' loop and I wish to jump to the next item in 'foreach
' when a certain condition occurs.
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();
}
'continue
' would jump to the beginning of the 'while
' loop not the 'foreach
' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用break关键字。 这将退出 while 循环并在其外部继续执行。 由于 while 之后没有任何内容,因此它将循环到 foreach 循环中的下一项。
实际上,更仔细地查看您的示例,您实际上希望能够在不退出 while 的情况下推进 for 循环。 您无法使用 foreach 循环来执行此操作,但您可以将 foreach 循环分解为其实际自动化的内容。 在 .NET 中,foreach 循环实际上呈现为对 IEnumerable 对象(即 this.ObjectNames 对象)的 .GetEnumerator() 调用。
foreach 循环基本上是这样的:
一旦有了这个结构,您就可以在 while 循环中调用 enumerator.MoveNext() 来前进到下一个元素。 所以你的代码将变成:
Use the break keyword. That will exit the while loop and continue execution outside it. Since you don't have anything after the while, it would loop around to the next item in the foreach loop.
Actually, looking at your example more closely, you actually want to be able to advance the for loop without exiting the while. You can't do this with a foreach loop, but you can break down a foreach loop to what it actually automates. In .NET, a foreach loop is actually rendered as a .GetEnumerator() call on the IEnumerable object (which your this.ObjectNames object is).
The foreach loop is basically this:
Once you have this structure, you can call enumerator.MoveNext() within your while loop to advance to the next element. So your code would become:
以下应该可以解决问题
The following should do the trick
break;
关键字将退出循环:The
break;
keyword will exit a loop:使用
goto
。(我猜人们会对这个回答感到生气,但我绝对认为它比所有其他选项更具可读性。)
Use
goto
.(I guess people will be mad with this response, but I definitely think it's more readable than all other options.)
您可以使用“中断;” 退出最里面的 while 或 foreach。
You can use "break;" to exit the innermost while or foreach.