重构代码以避免goto语句

thi*_*-Me -2 c# c#-4.0

在C#代码中避免goto语句的最佳方法是什么?我想摆脱goto语句重新启动for循环的执行

//some processing statements
//..
//..

start:
var rowCollection = GetData();
int RowCount = rowCollection.Count;
for(int iRow = 0; iRow < RowCount; iRow++)
{

  if(rowCollection[iRow]["Col"] > 0)
  {
     goto start;
  }

  else
  {
     //some processing statement
  }
}

//some more processing statements
//..
//..
Run Code Online (Sandbox Code Playgroud)

哪里,

  1. RowCount =从GetData()方法接收的行数
  2. rowCollection [iRow] ["Col"],"Col"是一些列名

And*_*rew 5

我认为你必须重构你的代码以使其更清晰,例如:

bool result;
do
{
    var rowCollection = GetData();
    result = ProcessData(rowCollection);
} while (!result);
Run Code Online (Sandbox Code Playgroud)

然后有这个方法:

bool ProcessData(RowCollection rowCollection)
{
    foreach (var item in rowCollection)
    {
        if (item["Col"] > 0)
        {
            return false;
        }
        else
        {
            // Do your stuff.
        }
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

这样您的代码就更具可读性和可维护性.