我需要从 foreach
循环中找出当前的行索引。
foreach (DataRow row in DataTable[0].Rows)
{
// I do stuff in here with the row, and if it throws an exception
// I need to pass out the row Index value to the catch statement
}
try/catch
block 中的任何一点都可能发生异常,但是如果我在 foreach
循环中使用增量计数器,并且异常发生在循环,我会得到一个无效的行,因为我已经将指针移动了一个。
我知道我可以在 foreach
范围之外声明一个 DataRow
,但是 foreach
在 try/catch 中
block 。我需要传递行索引,以便在 catch
语句中使用它。我应该说我的 DataTable
是在类级别的范围内。
这真的是获取当前行索引的唯一方法吗?还是有更简洁的实现?
编辑
因此,考虑更多,我可以使用 int
来存储当前行值,并像这样递增该值:
int i = 0;
try
{
// Some code here - which could throw an exception
foreach (DataRow row in DataTables[0].Rows)
{
// My stuff
i++;
}
// Some code here - which could throw an exception
}
catch
{
// Use the counter
DataRow row = DataTables[0].Rows[i];
}
但是,如果foreach
没有抛出异常,那么i
的值将大于表中的实际行数。显然,我可以在 foreach
循环之后执行 i--;
,但这似乎是一个真的肮脏的 hack。
最佳答案
一种肮脏的方法是将它包装在一个额外的 trycatch block 中:
int i = 0;
try
{
// Some code here - which could throw an exception
try{
foreach (DataRow row in DataTables[0].Rows)
{
// My stuff
i++;
}
// Some code here - which could throw an exception
}
catch{
i--;
throw;
}
}
catch
{
// Use the counter
DataRow row = DataTables[0].Rows[i];
}
这样你肯定知道异常是在 foreach 之后或期间抛出的,你总是得到正确的迭代器。
关于c# - 存储当前行索引的干净实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017240/