为什么 var 在“foreach (var row in table.Rows)"中计算为 System.Object?

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?)
本文介绍了为什么 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.所以,问题不在于 varforeach 子句中不起作用.

...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.

通过将类型显式放入其中,您基本上可以告诉编译器生成从 objectDataRow 的显式转换.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)