我应该使用goto语句? [英] Should I use goto statement?

查看:199
本文介绍了我应该使用goto语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一块类似下面的代码:

I have a piece of code like the following:

try
{
Work:

   while(true)
   {
      // Do some work repeatedly...
   }
}
catch(Exception)
{
   // Exception caught and now I can not continue 
   // to do my work properly

   // I have to reset the status before to continue to do my work
   ResetStatus();

   // Now I can return to do my work
   goto Work; 
}



进行比较,使用转到?或者这是一个好的解决方案?

Are there better alternatives compared to using goto? Or is this a good solution?

推荐答案

这听起来像你的真正的想要一个循环。我会写为:

It sounds like you really want a loop. I'd write it as:

bool successful = false;
while (!successful)
{
    try
    {
        while(true)
        {
            // I hope you have a break in here somewhere...
        }
        successful = true;
    }
    catch (...) 
    {
        ...
    }
}

您可能需要使用不要 / ,而循环代替;我的往往的喜欢直,而循环,但它是一个个人喜好,我可以看到它可能是更合适的位置。

You might want to use a do/while loop instead; I tend to prefer straight while loops, but it's a personal preference and I can see how it might be more appropriate here.

我的不会的使用虽然转到。它往往使困难代码遵循。

I wouldn't use goto though. It tends to make the code harder to follow.

当然,如果你的真正的希望有一个无限循环,只是把的try / catch 循环中:

Of course if you really want an infinite loop, just put the try/catch inside the loop:

while (true)
{
    try
    {
        ...
    }
    catch (Exception)
    {
        ...
    }
}

这篇关于我应该使用goto语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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