避免使用Goto

Mar*_*ram -2 c# goto

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

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

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

      //Use the bar object
}
Run Code Online (Sandbox Code Playgroud)

用以下内容替换它:

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

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

      //Use the bar object

}
Run Code Online (Sandbox Code Playgroud)

有任何想法或更好的方法来处理这个?

UPDATE

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

And*_*rei 9

使用while循环

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

    while (foo == null)
    {
        bar.addItem("Test");
        foo = bar.GetData();
    }
}
Run Code Online (Sandbox Code Playgroud)

更新.如果我理解你的真正目的:

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