为什么会出现与在C#的foreach“语句”VAR“变量没有智能感知? [英] Why is there no Intellisense with 'var' variables in 'foreach' statements in C#?

查看:156
本文介绍了为什么会出现与在C#的foreach“语句”VAR“变量没有智能感知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我,如果这是一个重复的,但它是一个小问题,我和我只能花这么长时间对我的好奇心。为什么,当我在foreach块使用隐式类型的循环变量,我没有得到任何的智能感知?推断的类型似乎是相当明显的。

Forgive me if this is a duplicate, but it's a minor issue for me and I can only spend so long on my curiosity. Why is it that when I use an implicitly typed loop variable in a foreach block, I get no Intellisense? The inferred type seems to be quite obvious.

我使用的ReSharper的,但是当我切换到智能感知VS我得到同样的行为,这并不认为这是难辞其咎的。

I am using ReSharper, but when I switch the Intellisense to VS I get the same behaviour, and this don't think it's to blame.

编辑:对不起,稍后,但我迭代DataTable.Rows,它采用了无类型ieterator,如马克如下解释

Sorry, a bit later, but I was iterating DataTable.Rows, which uses an untyped ieterator, as Marc explains below.

推荐答案

我怀疑你是列举数据没有类型 - 例如,一个很多的写在1.1事情只实现的IEnumerable ,并且没有一个自定义的迭代器(你实际上并不需要的IEnumerable< T> 做类型迭代 - 事实上,你甚至不需要的IEnumerable 使用的foreach ;很多1.1类型写道特殊枚举类型避免装箱/铸造等 - 大量的工作)。在许多情况下,这将是一个重大更改,以解决这些问题。

I suspect that the data you are enumerating is not typed - for example, a lot of things that were written in 1.1 only implement IEnumerable, and don't have a custom iterator (you don't actually need IEnumerable<T> to do typed iteration - and indeed you don't even need IEnumerable to use foreach; a lot of 1.1 typed wrote special enumerator types to avoid boxing/casting etc - lots of work). In many cases it would be a breaking change to fix them.

下面一个简单的例子是 PropertyDescriptorCollection

A trivial example here is PropertyDescriptorCollection:

var props = TypeDescriptor.GetProperties(obj);
foreach(PropertyDescriptor prop in props) {...} // fine

但实际上, PropertDescriptorCollection 的枚举就是的IEnumerator ,所以电流对象 - 因此您总能获得对象当你使用无功

but actually, PropertDescriptorCollection's enumerator is just IEnumerator, so Current is object - and hence you'll always get object when you use var:

var props = TypeDescriptor.GetProperties(obj);
foreach(var prop in props) {...} // prop is "object"

此相反的是(平均1.1) StringCollection ;这有一个自定义枚举( StringEnumerator );因此,如果你使用的foreach VAR ,你会得到字符串(而不是对象)。

Contrast this to the (equally 1.1) StringCollection; this has a custom enumerator (StringEnumerator); so if you used foreach with var, you'd get string (not object).

在任何2.0及以上,这将是有理由期待更好的打字,有两个原因:

In anything 2.0 and above, it would be reasonable to expect better typing, for two reasons:

  • 泛型(为简单的情况下),从而能够合理地写强类型集合
  • 迭代块(对于非平凡例),使得有可能无需编写自定义迭代疯

不过,即使如此,还是有,当你没有得到你所期望的类型案件;您可以(也许更清楚)手动指定的类型,或者使用演员LT; T&GT;() / OfType&LT; T&GT;()

But even then there are still cases when you don't get the type you expect; you can either (and perhaps more clearly) specify the type manually, or use Cast<T>() / OfType<T>().

这篇关于为什么会出现与在C#的foreach“语句”VAR“变量没有智能感知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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