在以下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();
}
'continue
'会跳转到“while
”循环的开头而不是“foreach
”循环。
这里有一个关键字,或者我应该使用我不喜欢的goto。
答案 0 :(得分:9)
使用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
}
一旦有了这个结构,就可以在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
}
}
答案 1 :(得分:3)
以下应该做的伎俩
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
this.ExecuteSomeCode();
while (this.boolValue)
{
if (this.MoveToNextObject())
{
// What should go here to jump to next object.
break;
}
}
if (! this.boolValue) continue; // continue foreach
this.ExecuteSomeOtherCode();
}
答案 2 :(得分:2)
break;
关键字将退出循环:
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
while (this.boolValue)
{
// 'continue' would jump to here.
if (this.MoveToNextObject())
{
break;
}
this.boolValue = this.ResumeWhileLoop();
}
}
答案 3 :(得分:1)
使用goto
。
(我想人们会对这种反应感到生气,但我绝对认为它比所有其他选择更具可读性。)
答案 4 :(得分:0)
你可以使用“break;”离开最里面或者前进。