为什么我不能做的foreach(在DataTable.Rows VAR项)?我不、能做、foreach、VAR

2023-09-02 21:54:43 作者:写生的少女

还有一个原因,为什么我不能做到以下几点:

Is there a reason why I can't do the following:

foreach (var Item in DataTable.Rows) {

,而不必做

foreach (DataRow Item in DataTable.Rows) {

我还以为这是可能的,就像它在其它数据类型。例如:

I would have thought this was possible, like it is on other datatypes. For example:

foreach (var Employee in Staff) { // string[] Staff etc...

当我尝试的第一个foreach循环,我得到了错误的 CS0021:无法应用索引与[]以类型的前pression对象

When I try the first foreach loop, I get the the error CS0021: Cannot apply indexing with [] to an expression of type 'object'.

为什么不能编译器弄清楚,.Rows返回数据行的集合?

Why can't the compiler figure out that .Rows returns a collections of DataRows?

推荐答案

有效地返回的IEnumerable DataRowCollection ),因此编译器只能挑对象作为类型 VAR 。使用 Rows.Cast< D​​ataRow的> 如果你想使用 VAR

Rows effectively returns IEnumerable (DataRowCollection), so the compiler can only pick object as the type for var. Use Rows.Cast<DataRow> if you want to use var.

铸造 可枚举,所以你必须包括System.Linq的。

Cast is defined on Enumerable, so you have to include System.Linq.