为什么我不能做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?
推荐答案
行
有效地返回 IEnumerable
code> DataRowCollection ),所以编译器只能选择对象
作为 var $ c的类型$ c>。如果要使用
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屋!