Why does var evaluate to System.Object in quot;foreach (var row in table.Rows)quot;?(为什么 var 在“foreach (var row in table.Rows)中计算为 System.Object?)
问题描述
当我输入这个 foreach 语句时...
When I enter this foreach statement...
foreach (var row in table.Rows)
...var 的工具提示说 class System.Object
...the tooltip for var says class System.Object
我很困惑为什么它不是 class System.Data.DataRow.
I'm confused why it's not class System.Data.DataRow.
(如果您想知道,是的,我的代码文件顶部有 using System.Data.)
(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 计算结果为 struct 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 的答案,因为它确实回答了我的问题,但 Oliver 回答了我应该问的问题 :)
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 :)
推荐答案
那是因为 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.
通过将类型显式放入其中,您基本上可以告诉编译器生成从 object 到 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 在“foreach (var row in table.Rows)"中计算为 System.Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 var 在“foreach (var row in table.Rows)"中计算为 System.Object?
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
