我有一个项目,将 SQL 中的一些数据存储在 DataTable
中然后映射每个 DataRow
到自定义类实例。
当我循环Rows
时属性(类型为 DataRowCollection
),没有类型推断。
所以这不起作用:
var dt = new DataTable();
foreach(var row in dt.Rows)
{
int id = Int32.Parse(row.ItemArray[0].ToString());
// doesn't compile
}
但这确实:
var dt = new DataTable();
foreach(DataRow row in dt.Rows)
{
int id = Int32.Parse(row.ItemArray[0].ToString());
}
为什么编译器无法弄清楚 row
的类型是?可以var
在枚举 DataRowCollection
的情况下,关键字代表其他内容?除了数据行之外,还有其他东西可以在 DataRowCollection
中枚举吗? ?
这就是您需要明确表达的原因吗?
最佳答案
因为DataRowCollection
实现IEnumerable
(通过 InternalDataCollectionBase
)但不是通用的,输入 IEnumerable<T>
。这个类太老了。
通过在 foreach
中指定类型你正在隐式地转换它。
关于c# - DataRowCollection 没有类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024686/