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

查看:525
本文介绍了为什么我不能做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?

推荐答案

有效地返回 IEnumerable code> DataRowCollection ),所以编译器只能选择对象作为 var 。如果要使用 var ,请使用 Rows.Cast< DataRow>

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 枚举,所以你必须包括System.Linq。

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

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

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