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?
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
