简体   繁体   中英

C# DataSet foreach

I'm using DataSet and when I iterate at columns with foreach loop I can't get ColumnName (if using var keyword):

eg

DataTable table1 = new DataTable("patients");
table1.Columns.Add("name");
table1.Columns.Add("id");
table1.Rows.Add("sam", 1);
table1.Rows.Add("mark", 2);

And than using foreach:

在此处输入图片说明

But if foreach statement is explicitly defined:

在此处输入图片说明

Everything is ok. I know that foreach is syntactic sugar for Enumarator. Is it some kind of legacy and lack of Generics ?

Is it some kind of legacy and lack of Generics?

Yes. This code was written in C# 1.0, before generics existed.

DataTable.Columns is a DataColumnCollection. DataColumnCollection implements IEnumerable, not IEnumerable<DataColumn>. The foreach statement performs a cast for whichever type you specify. Var specifies what the enumerator method returns (which is this case is Object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM