在对如何突破二次循环做了一些研究之后
while (true) { // Main Loop
for (int I = 0; I < 15; I++) { // Secondary loop
// Do Something
break; // Break main loop?
}
}
大多数人建议调用'goto'函数
看下面的例子:
while (true) { // Main Loop
for (int I = 0; I < 15; I++) { // Secondary Loop
// Do Something
goto ContinueOn; // Breaks the main loop
}
}
ContinueOn:
但是;我经常听说“goto”语句是不好的做法。下图完美地说明了我的观点:
所以
- goto 语句到底有多糟糕,为什么?
- 有没有比使用“goto”语句更有效的中断主循环的方法?
最佳答案
编辑:
How bad is the goto statement really, and why?
这取决于具体情况。我不记得什么时候我发现它使代码比重构更具可读性。这也取决于您个人对可读性的看法——有些人比其他人更不喜欢它,这从其他答案中可以清楚地看出。 (有趣的是,它广泛用于生成的代码 - C# 5 中的所有 async/await 代码实际上都基于很多 goto)。
问题在于,goto
往往被使用的情况往往 是重构无论如何都会有所帮助的情况 - 而 goto
坚持使用随着代码变得更复杂而变得更难遵循的解决方案。
Is there a more effective way to break the main loop than using the 'goto' statement?
当然。将您的方法提取到一个单独的函数中:
while (ProcessValues(...))
{
// Body left deliberately empty
}
...
private bool ProcessValues()
{
for (int i = 0; i < 15; i++)
{
// Do something
return false;
}
return true;
}
我通常更喜欢这样做,而不是引入一个额外的局部变量来跟踪“我完成了吗”——当然,这也行。
关于c# - 使用 'goto' 语句不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906056/