清理存储当前行索引的实现

Nei*_*ght 5 c# datatable implementation

我需要找出foreach循环中当前Row索引的内容.

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

try/catch块中的任何一点都可能发生异常,但如果我在foreach循环中使用增量计数器,并且异常发生在循环之外,我将得到一个无效行,因为我已经将指针移动了一个.

我知道我可以DataRowforeach范围之外声明,但是foreach在一个try/catch区块内.我需要传递Row索引,以便我可以在catch语句中使用它.我应该说我DataTable在班级范围内.

这真的是获取当前Row索引的唯一方法吗?或者是否有更清洁的实施?

编辑

所以,考虑到这一点,我可以用a 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];
}
Run Code Online (Sandbox Code Playgroud)

但是,如果foreach不抛出异常,那么值i将大于表中的实际行数.显然,我可以i--;foreach循环之后做,但这似乎是一个非常肮脏的黑客.

Iga*_*hka 0

一种肮脏的方法是将其包装在一个额外的 trycatch 块中:

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

这样你肯定知道异常是在 foreach 之后或 durring 之后抛出的,并且你总是得到正确的迭代器。