'转到'这是坏? [英] 'Goto' is this bad?

查看:177
本文介绍了'转到'这是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过二次回路做就如何打破一些研制后

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?
   }
}

大多数人建议称之为转到功能
结果展望如下面的例子:

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语句真的,为什么?

  • 是否有打破主循环比使用'转到'语句更有效的方式?

  • How bad is the goto statement really, and why?
  • Is there a more effective way to break the main loop than using the 'goto' statement?

推荐答案

编辑:

有多糟糕goto语句真的,为什么?

How bad is the goto statement really, and why?

这取决于确切的情况。我不记得任何时候,我发现它提出的code比重构更易读。这也取决于可读性,您个人的观点 - 有些人不喜欢比别人多,因为从其他的答案清晰。 (作为兴趣点,它广泛用于的生成的code - 所有的异步/的await $ C $在C#5℃是基于有效很多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).

问题是,要使用其中转到趋于情况下的往往的是什么样的情况下重构艾滋病的事情呢 - 而转到与变得更难遵循为code的解决方案枝变得更加复杂。

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.

有没有打破主循环比使用'转到'语句更有效的方式?

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;
}

我一般preFER这样做了引入额外的本地变量来跟踪有我完了。 - 尽管这会努力的,当然

I generally prefer doing this over introducing an extra local variable to keep track of "have I finished" - although that will work to, of course.

这篇关于'转到'这是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆