为什么VAR计算为System.Object中的"的foreach(在table.Rows VAR行)QUOT;? [英] Why does var evaluate to System.Object in "foreach (var row in table.Rows)"?

查看:197
本文介绍了为什么VAR计算为System.Object中的"的foreach(在table.Rows VAR行)QUOT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我进入这个的foreach 语句...

When I enter this foreach statement...

foreach (var row in table.Rows)

...工具提示为无功说类System.Object的

我很困惑,为什么这不是类的System.Data.DataRow

I'm confused why it's not class System.Data.DataRow.

(如果你想知道,是的,我有使用System.Data这我的code文件的顶部。)

(In case you're wondering, yes, I have using System.Data at the top of my code file.)

如果我宣布了明确的类型,如...

If I declare the type explicitly, as in...

foreach (DataRow row in table.Rows)

...它工作正常,没有错误。

...it works fine with no errors.

另外,如果我做的......

Also if I do...

var numbers = new int[] { 1, 2, 3 };
foreach (var number in numbers)

... VAR的计算结果为结构System.Int32的。所以,问题不在于 VAR 的foreach 子句不起作用。

...var evaluates to struct System.Int32. So, the problem is not that var doesn't work in a foreach clause.

所以,有一些奇怪的 DataRowCollection ,其中的项目不会自动计算为的DataRow 。但我无法弄清楚它是什么。有没有人有一个解释?

So, there's something strange about DataRowCollection where the items don't automatically evaluate to DataRow. But I can't figure out what it is. Does anyone have an explanation?

更新

我真的撕裂这回答标记(codeKA和Oliver)......最后,我决定以纪念codeKA的,因为它真实地回答我的问题,但奥利弗回答我应该是问题问:)

I was really torn which answer to mark (Codeka and Oliver)...In the end, I decided to mark Codeka's because it truly answers my question, but Oliver answers the question I should have been asking :)

推荐答案

这是因为,<一个href="http://msdn.microsoft.com/en-us/library/system.data.datarowcollection%28v=VS.100%29.aspx">DataRowCollection类只能实现的IEnumerable 的非通用版本。因此,编译器不知道该变量的类型。

That's because the DataRowCollection class only implements the non-generic version of IEnumerable. So the compiler doesn't know what the type of the variable is.

通过明确地把类型在那里,你基本上告诉编译器生成一个明确的转换,从对象的DataRow

By explicitly putting the type in there, you basically tell the compiler to generate an explicit cast from object to DataRow.

这是一个问题,你会发现有许多加回在.NET 1.x的天藏品和类,仿制药可用了。

This is a problem you'll find with many of the collections and classes added back in the .NET 1.x days, before generics were available.

这篇关于为什么VAR计算为System.Object中的&QUOT;的foreach(在table.Rows VAR行)QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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