Why does var evaluate to System.Object in “foreach (var row in table.Rows)”?

前端 未结 2 544
南方客
南方客 2020-12-02 01:48

When I enter this foreach statement...

foreach (var row in table.Rows)

...the tooltip for var says class System.Object

相关标签:
2条回答
  • 2020-12-02 02:21

    That's because the DataRowCollection class only implements the non-generic version of IEnumerable. So the compiler doesn't know what the type of the variable is.

    By explicitly putting the type in there, you basically tell the compiler to generate an explicit cast from object to DataRow.

    This is a problem you'll find with many of the collections and classes added back in the .NET 1.x days, before generics were available.

    0 讨论(0)
  • 2020-12-02 02:24

    While codeka is right, there exists some other methods to get more convenience into this DataTable and DataRowstuff.

    With .Net 3.5 you can add the assembly System.Data.DataSetExtensions.

    It contains some extension functions like AsEnumerable(this System.Data.DataTable) or Field<T>(this System.Data.DataRow, int) with it you can call it within a foreach loop and cast the column directly into the proper type:

    int columnIndex = 2;
    
    foreach(var row in MyDataTable.AsEnumerable())
    {
        var content = row.Field<double>(columnIndex);
    }
    
    0 讨论(0)
提交回复
热议问题