为什么VAR推断类型对象,而不是在XmlNode的循环的XmlNodeList?

编程入门 行业动态 更新时间:2024-10-10 19:22:57
本文介绍了为什么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?

本文发布于:2023-11-11 08:20:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   而不   推断   对象   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!