使用“goto"语句不好吗? [英] Is using a 'goto' statement bad?
问题描述
研究如何突破二次循环后
After doing some reseach on how to break through a secondary loop
while (true) { // Main Loop
for (int I = 0; I < 15; I++) { // Secondary loop
// Do Something
break; // Break main loop?
}
}
大多数人推荐调用'goto'函数
看下面的例子:
most people recommended to call the 'goto' function
Looking as the following example:
while (true) { // Main Loop
for (int I = 0; I < 15; I++) { // Secondary Loop
// Do Something
goto ContinueOn; // Breaks the main loop
}
}
ContinueOn:
然而;我经常听说goto"语句是不好的做法.下图完美地说明了我的观点:
However; I have often heard that the 'goto' statement is bad practice. The picture below is perfectly illustrating my point:
- goto 语句到底有多糟糕,为什么?
- 有没有比使用goto"语句更有效的中断主循环的方法?
推荐答案
goto 语句到底有多糟糕,为什么?
How bad is the goto statement really, and why?
这取决于具体情况.我不记得有什么时候我发现它使代码比重构更具可读性.这也取决于您对可读性的个人看法 - 有些人比其他人更不喜欢它,从其他答案中可以清楚地看出.(有趣的是,它广泛用于生成代码 - C# 5 中的所有 async/await 代码实际上都基于大量 goto.
It depends on the exact situation. I can't remember any time where I found it made the code more readable than refactoring. It also depends on your personal view of readability - some people dislike it more than others, as is clear from the other answers. (As a point of interest, it's widely used in generated code - all of the async/await code in C# 5 is based on effectively a lot of gotos).
问题在于,goto
倾向于被使用的情况倾向于是重构有助于事情的那种情况 - 而 goto
坚持使用随着代码变得更复杂而变得更难遵循的解决方案.
The problem is that situations where goto
tends to be used tend to be the kind of situations where refactoring aids things anyway - whereas goto
sticks with a solution which becomes harder to follow as the code gets more complicated.
有没有比使用goto"语句更有效的中断主循环的方法?
Is there a more effective way to break the main loop than using the 'goto' statement?
绝对的.将您的方法提取到一个单独的函数中:
Absolutely. Extract your method out into a separate function:
while (ProcessValues(...))
{
// Body left deliberately empty
}
...
private bool ProcessValues()
{
for (int i = 0; i < 15; i++)
{
// Do something
return false;
}
return true;
}
我通常更喜欢这样做而不是引入一个额外的局部变量来跟踪我完成了吗"- 当然这也行.
I generally prefer doing this over introducing an extra local variable to keep track of "have I finished" - although that will work too, of course.
这篇关于使用“goto"语句不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!