为什么我不能做 foreach(DataTable.Rows 中的 var Item)? [英] Why can't I do foreach (var Item in DataTable.Rows)?
问题描述
为什么我不能执行以下操作:
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:无法将 [] 索引应用到类型为对象"的表达式.
When I try the first foreach loop, I get the the error CS0021: Cannot apply indexing with [] to an expression of type 'object'.
为什么编译器无法确定 .Rows 返回的是 DataRows 的集合?
Why can't the compiler figure out that .Rows returns a collections of DataRows?
推荐答案
Rows
有效返回 IEnumerable
(DataRowCollection
),因此编译器可以只选择 object
作为 var
的类型.如果您想使用 var
,请使用 Rows.Cast
.
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
.
Cast
在 Enumerable 上定义,所以你必须包含 System.Linq.
Cast
is defined on Enumerable, so you have to include System.Linq.
这篇关于为什么我不能做 foreach(DataTable.Rows 中的 var Item)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!