[英]C# - repeat for loop without using goto
最近在开发一个计算器程序时,发现自己多次使用goto
来重新启动一个 for 循环。 例子:
StartLoop:
for (int i = 0; i < length; i++)
{
if (items[i] == condition)
{
//Do something
goto StartLoop:
}
}
我知道应该避免goto
但是我还需要什么其他方式来重新启动循环?
只需设置i
的值:
int length = 9;
for (int i = 0; i < length; i++)
{
Console.WriteLine(i);
if (i == 7)
{
i = -1;
}
}
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
0
1
2
3
4
5
...
根据 /u/Tim Schmelter 的评论,将逻辑拆分为多个方法可能会更清晰。
如果将循环放入布尔返回方法,则可以返回一个值,该值指示循环是否过早终止。 有无数种方法可以做到这一点; 这是一个例子:
void processItemsUntilComplete(int[] items)
{
static bool condition(int item) => item == 42;
while (!processItemsUntil(items, condition))
{
// Keep looping until processItems() returns true to indicate that it completed.
}
}
/// <summary>Processes items until a certain condition occurs.</summary>
/// <returns>True if all the items were processed; false if the processing was interrupted because the condition was true.</returns>
bool processItemsUntil(int[] items, Predicate<int> condition)
{
foreach (var item in items)
{
if (condition(item))
return false;
// Other processing.
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.