在foreach内继续
-
05-07-2019 - |
题
在以下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。
解决方案
以下应该做的伎俩
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();
}
其他提示
使用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
}
}
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();
}
}
使用转到
。
(我想人们会对这种反应感到生气,但我绝对认为它比所有其他选项更具可读性。)
你可以使用“break;”离开最里面或者前进。
不隶属于 StackOverflow