我应该使用goto声明吗?

Nic*_*ick 4 c# goto

我有一段代码如下:

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; 
}
Run Code Online (Sandbox Code Playgroud)

与使用相比,有更好的替代品goto吗?或者这是一个很好的解决方案?

Jon*_*eet 16

听起来你真的想要一个循环.我把它写成:

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

您可能希望使用do/ whileloop; 我倾向于选择直接while循环,但这是个人偏好,我可以看到它在这里更合适.

不会goto.它往往会使代码更难以遵循.

当然,如果你真的想要一个无限循环,只需把它try/catch放在循环内:

while (true)
{
    try
    {
        ...
    }
    catch (Exception)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ Fake.It.Til.U.Make.It:我不知道你的意思,我很害怕. (4认同)

Ale*_*kov 10

Goto是很少适当的构造使用.使用会使99%的查看代码的人感到困惑,甚至在技术上正确使用它会大大减慢对代码的理解.

在大多数情况下,重构代码将消除(或使用)的需要goto.即在你的特殊情况下,你可以简单地try/catch在里面移动while(true).将迭代的内部代码转换为单独的函数可能会使它更加清晰.

while(true)
{
  try
  {
      // 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();
  }
}
Run Code Online (Sandbox Code Playgroud)