为什么VAR推断类型对象,而不是在XmlNode的循环的XmlNodeList? [英] Why does var infer type object and not XmlNode in XmlNodeList loop?

查看:119
本文介绍了为什么VAR推断类型对象,而不是在XmlNode的循环的XmlNodeList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个遍历像这样

foreach (XmlNode foo in xmlNodeList) {string baa = foo.Attributes["baa"].Value;}

一切正常 - 美孚显然类型的 XmlNode的的和VS.NET IDE显示方法和字段。

everything works as expected - foo is clearly of type XmlNode and the VS.NET IDE shows methods and fields.

在另一方面

foreach (var foo in xmlNodeList) { string baa = foo.Attributes["baa"].Value; }



不编译因为这里foo是类型的对象的。类型推断类作品,但推断的对象

is not compiling because here foo is of type object. Type inference sort of works but infers object.

显然,XmlNodeList中的元素的有一个的定义类型的不是,但分配他们的XMLNode的不是var做了隐式(铸造或拆箱)。

Apparently, the elements of XmlNodeList are not of one defined type, but assigning them to XmlNode instead of var does something implicitly (casting or unboxing).

第一个问题:什么是背后的机制

First question: what's the mechanism behind that?

二(相关的)问题:如何找到类型可以在这种循环的使用?请问VS.NET IDE帮助?

Second (related) question: how to find the types one can use in this kind of loop? Does the VS.NET IDE help?

推荐答案

的XmlNodeList 只实现非泛型的IEnumerable 接口,而不是像的IEnumerable<&XmlNode的GT; 泛型。这可以防止其元素的强类型,直到你施放适当,所以编译器别无选择,只能映射隐式类型声明在你的foreach对象

XmlNodeList implements only the non-generic IEnumerable interface, and not something like IEnumerable<XmlNode> with generics. This prevents strong typing of its elements until you cast appropriately, so the compiler has no choice but to map the implicit type declaration to object in your foreach.

如果你坚持使用 VAR 关键字,您可以施放的元素的XmlNodeList 像这样:

If you insist on using the var keyword, you can cast the elements of xmlNodeList like so:

foreach (var foo in xmlNodeList.Cast<XmlNode>())
{
    string baa = foo.Attributes["baa"].Value;
}



但是,这是丑陋的,而且需要更多的击键反正。您可能也只是明确声明 XmlNode的富,并让投的foreach为你的飞行。

But that's ugly, and requires more keystrokes anyway. You may as well just explicitly declare XmlNode foo, and let the foreach cast it for you on the fly.

这篇关于为什么VAR推断类型对象,而不是在XmlNode的循环的XmlNodeList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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