为什么我不能做 foreach(DataTable.Rows 中的 var Item)? [英] Why can't I do foreach (var Item in DataTable.Rows)?

查看:11
本文介绍了为什么我不能做 foreach(DataTable.Rows 中的 var Item)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能执行以下操作:

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.

CastEnumerable 上定义,所以你必须包含 System.Linq.

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

这篇关于为什么我不能做 foreach(DataTable.Rows 中的 var Item)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆