ahm*_*iee 3 c# foreach loops while-loop c#-4.0
我有这个代码:
foreach(int i in Directions)
{
if (IsDowner(i))
{
while (IsDowner(i))
{
continue;
//if (i >= Directions.Count)
//{
// break;
//}
}
//if (i >= Directions.Count)
//{
// break;
//}
if (IsForward(i))
{
continue;
//if (i >= Directions.Count)
//{
// break;
//}
//check = true;
}
//if (i >= Directions.Count)
//{
// break;
//}
if (IsUpper(i))
{
//if (i >= Directions.Count)
//{
// break;
//}
num++;
//check = false;
}
//if (check)
//{
// num++;
//}
}
}
Run Code Online (Sandbox Code Playgroud)
但我想有continue
对foreach
在while
循环.我怎样才能做到这一点?
你不能从内部循环继续外循环.您有两种选择:
坏的:在打破内部循环之前设置一个布尔标志,然后检查这个标志并在设置时继续.
好的:只需将您的大spagetti代码重构为一组函数,这样就不会有内部循环.
您可以break
退出while
循环并继续进行外foreach
循环的下一次迭代,这将开始一个新while
循环:
foreach(int i in Directions)
{
while (IsDowner(i))
{
break;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你在while
循环之后有一些其他的代码,你不想在这种情况下执行你可以使用一个布尔变量,它将在断开while
循环之前设置,这样这段代码就不会执行并自动跳转到循环的下一次迭代forach
:
foreach(int i in Directions)
{
bool broken = false;
while (IsDowner(i))
{
// if some condition =>
broken = true;
break;
}
if (broken)
{
// we have broken out of the inner while loop
// and we don't want to execute the code afterwards
// so we are continuing on the next iteration of the
// outer foreach loop
continue;
}
// execute some other code
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1719 次 |
最近记录: |