避免使用Goto

时间:2013-06-03 17:15:03

标签: c# goto

全部 -        我正在重构一些旧的代码,我正在寻找减少(或完全不消除它)GoTo语句的方法。我有一段代码如下:

public void GetData()
{
  TryAgain:
      Foo foo = bar.GetData();

      if(foo == null)
      {
          bar.addItem("Test");
          goto TryAgain;
      }

      //Use the bar object
}

用以下内容替换它:

public void GetData()
{
      Foo foo = bar.GetData();

      if(foo == null)
      {
          bar.addItem("Test");
          GetData();
          return;
      }

      //Use the bar object

}

有任何想法或更好的方法来解决这个问题吗?

更新

首先,这不是我的实际代码,为了简洁起见,我创建了这个代码段。接下来请假设一旦将值添加到bar,则将绕过IF语句,代码部分将继续并使用bar对象。我想只创建一个方法,首先检查以确保bar对象不为null,如果不是,则继续运行方法中的其余代码。对不起,感到困惑。

6 个答案:

答案 0 :(得分:9)

使用while循环

public void GetData()
{
    Foo foo = bar.GetData();

    while (foo == null)
    {
        bar.addItem("Test");
        foo = bar.GetData();
    }
}

<强>更新即可。如果我理解你的真正目的:

public void GetData()
{
    Foo foo = bar.GetData();    
    if (foo == null)
    {
        bar.addItem("Test");
        // following the assumption
        // "once a value has been added to bar then the IF statement will be bypassed"
        // there is no need for another GetData call - bar object is in valid state now
    }

    //Use the bar object
}

答案 1 :(得分:3)

public void GetData()
{
    Foo foo;    
    while ((foo = bar.GetData()) == null)
        bar.addItem("Test");
}

答案 2 :(得分:1)

public void GetData()
{
  while(true)
 {
      Foo foo = bar.GetData();

      if(foo == null)
      {
          bar.addItem("Test");
      }
      else break;
 }
}

答案 3 :(得分:1)

根据您的更新

更新,我可能会使用以下代码:

public void GetData()
{
    Foo foo = bar.GetData();

    if (foo == null)
    {
        bar.addItem("Test");
        foo = bar.GetData();

        Debug.Assert(foo != null, "Hey, I thought that would give me a value!");
    }

    // do something with foo
}

答案 4 :(得分:1)

你没有使用foo对象,所以你可以摆脱它。

public void GetData()
{
    while (bar.GetData() == null)
        bar.addItem("Test");

    //Use the bar object
}

答案 5 :(得分:-3)

您基本上描述了.Net 4.5中创建的await/async模式。如果你控制了足够的代码来实现它,那么有问题的代码就变成了这样:

// bar.addItem would need to be done in GetDataAsync if it is important
Foo foo = await bar.GetDataAsync();

最好的答案是@Andrei描述的while循环方法。

MSDN Asynchronous programming

相关问题