重构代码以避免 goto 语句
本文关键字:goto 语句 代码 重构 | 更新日期: 2023-09-27 18:34:54
避免
在 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
//..
//..
哪里
- RowCount = 从 GetData(( 方法接收的行数
- rowCollection[iRow]["Col"], "Col" 是某个列名
我认为您必须重构代码以使其更清晰,例如:
bool result;
do
{
var rowCollection = GetData();
result = ProcessData(rowCollection);
} while (!result);
然后有这个方法:
bool ProcessData(RowCollection rowCollection)
{
foreach (var item in rowCollection)
{
if (item["Col"] > 0)
{
return false;
}
else
{
// Do your stuff.
}
}
return true;
}
这样,您的代码更具可读性和可维护性。
var rowCollection = GetData();
for(int iRow = 0; iRow < RowCount; iRow++)
{
if(iRow["Col"] > 0)
{
rowCollection = GetData();
RowCount=rowCollection.length();
irow = 0;
}
else
{
//some processing statement
}
}
不太确定你的用例是什么,但你可以这样做。
var rowCollection = GetData();
for(int iRow = 0; iRow < RowCount; iRow++)
{
if(iRow["Col"] > 0)
{
rowCollection = GetData();
irow = 0;
}
else
{
//some processing statement
}
}