Use of C# var for implicit typing of System.Data.Datarow

前端 未结 3 909
闹比i
闹比i 2021-02-12 18:54
foreach (var row in table.Rows)
{
     DoSomethingWith(row);
}

Assuming that I\'m working with a standard System.Data.DataTable (which has

相关标签:
3条回答
  • 2021-02-12 19:21

    table.Rows is a DataRowCollection which is IEnumberable ( and not IEnumerable<T>, T being DataRow), so it is not strongly typed to a DataRow, but a object i.e it is a collection of objects.

    There is a DataTable extensions which you can use though - http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx

    foreach (var row in table.AsEnumerable())
    {
    
    }
    
    0 讨论(0)
  • 2021-02-12 19:28

    That's because Rows is DataRowCollection, which in turn is IEnumerable and not IEnumerable<DataRow>, which means that type inferred will be object.

    When you explicitly state type in foreach, you instruct c# to add cast to each call, which is why it works.

    0 讨论(0)
  • 2021-02-12 19:28

    An implicit cast happens. Also note that an InvalidCastException can be thrown if the cast isn't possible.

    0 讨论(0)
提交回复
热议问题