C# 如何继续上循环
我有以下代码:C# 如何继续上循环,c#,c#-4.0,loops,foreach,while-loop,C#,C# 4.0,Loops,Foreach,While Loop,我有以下代码: foreach(int i in Directions) { if (IsDowner(i)) { while (IsDowner(i)) { continue; //if (i >= Directions.Count) //{
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++;
//}
}
}
但是我想在
while
循环中继续forforeach
。我如何才能做到这一点?您可以中断while
循环,进入外部foreach
循环的下一次迭代,该循环将启动新的while
循环:
foreach(int i in Directions)
{
while (IsDowner(i))
{
break;
}
}
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
}
如果在while
循环之后有一些其他代码,在这种情况下,您不希望执行这些代码,那么可以使用一个布尔变量,该变量将在中断while
循环之前设置,以便此代码不会执行,并自动跳转到forach
循环的下一次迭代:
foreach(int i in Directions)
{
while (IsDowner(i))
{
break;
}
}
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
}
不能从内部循环继续外部循环。
您有两个选择:
坏的一个:在中断内部循环之前设置一个布尔标志,然后检查此标志,如果已设置,则继续
好的方法是:简单地将你的大spagetti代码重构成一组函数,这样你就不会有内部循环
在我看来,在复杂的嵌套循环中使用goto是合理的(是否应该避免使用复杂的嵌套循环是另一个问题)
您可以这样做:
foreach(int i in Directions)
{
while (IsDowner(i))
{
goto continueMainLoop;
}
//There be code here
continueMainLoop:
}
如果其他人必须处理代码,请务必小心,确保他们不害怕跳转。您可以尝试对内部for循环使用谓词,如:
foreach (item it in firstList)
{
if (2ndList.Exists(x => it.Name.StartsWith(x))) //use predicate instead of for loop.
{
continue;
}
}
希望这能对您有所帮助。但在while循环之后,我有另一个代码,我想用它们和下一个foreach变量(I)。@Ahmadalishafie,您可以使用布尔变量。问题编辑。但是按照您的方式,我的代码中有许多嵌套的if,而不是使用if(!break){…}
您可以使用if(break)continue
@Ahmadalishafie,你不能从内环继续外环。您首先需要打破内部循环。正如Piotr Auguscik建议的那样,你可以扭转这种状况。我用一个例子更新了我的答案。相关: