var关键字并不总是工作吗? [英] var keyword not always working?
问题描述
C#,2010年VS有人请解释为什么我不能在我下面的代码中使用 VAR
!
C#, VS 2010. Somebody, please explain why I can't use var
in my code below!
var props = TypeDescriptor.GetProperties(adapter);
// error CS1061: 'object' does not contain a definition for 'DisplayName'
foreach (var prop in props)
{
string name = prop.DisplayName;
}
// No error
foreach (PropertyDescriptor prop in props)
{
string name = prop.DisplayName;
}
TypeDescriptor.GetProperties
返回 PropertyDescriptorCollection
与的PropertyDescriptor
的实例。为什么不能编译器看?
TypeDescriptor.GetProperties
returns a PropertyDescriptorCollection
with instances of PropertyDescriptor
. Why can't the compiler see this?
推荐答案
TypeDescriptor.GetProperties
返回一个类只有一个 的GetEnumerator
实现,返回非通用的IEnumerator
。该类型的 电流<中/ code>
属性是对象
- 这是唯一的类型编译器可以推断出,所以这类型的道具
变量会。
TypeDescriptor.GetProperties
returns a class that only has a GetEnumerator
implementation that returns the non-generic IEnumerator
. The type of its Current
property is object
- and that's the only type the compiler can infer, so that's the type your prop
variable will be.
第二个的foreach
使用的PropertyDescriptor
而不是 VAR
为托
实际执行从对象
到的PropertyDescriptor
The second foreach
that uses PropertyDescriptor
instead of var
as the type of prop
actually performs a conversion from object
to PropertyDescriptor
.
假设这段代码:
PropertyDescriptor x = // get from somewhere;
object o = x;
PropertyDescriptor y = (PropertyDescriptor)o;
同样在发生第二个的foreach
。循环为每个项目
您可以添加一个演员LT; PropertyDescriptor的>()
来得到一个通用的的IEnumerable< T>
与的GetEnumerator
返回 IEnumerator的< T>
。如果你这样做,你可以使用 VAR
在的foreach
循环:
You could add a Cast<PropertyDescriptor>()
to get a generic IEnumerable<T>
with an implementation of GetEnumerator
that returns IEnumerator<T>
. If you do this, you can use var
in the foreach
loop:
var props = TypeDescriptor.GetProperties(adapter).Cast<PropertyDescriptor>();
// No error
foreach (var prop in props)
{
string name = prop.DisplayName;
}
这篇关于var关键字并不总是工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!