C#,VS 2010。有人,请解释为什么我不能在下面的代码中使用 var
!
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
返回带有 PropertyDescriptor
实例的 PropertyDescriptorCollection
。为什么编译器看不到这个?
最佳答案
TypeDescriptor.GetProperties
返回一个只有 GetEnumerator
的类返回非通用 IEnumerator
的实现.其类型 Current
属性是 object
- 这是编译器可以推断的唯一类型,所以这就是你的类型 prop
变量将是。
第二个foreach
使用PropertyDescriptor
而不是 var
作为 prop
的类型实际上从 object
执行转换至 PropertyDescriptor
.
假设这段代码:
PropertyDescriptor x = // get from somewhere;
object o = x;
PropertyDescriptor y = (PropertyDescriptor)o;
同样的事情发生在第二个foreach
循环每个项目。
您可以添加 Cast<PropertyDescriptor>()
获得通用 IEnumerable<T>
实现 GetEnumerator
返回 IEnumerator<T>
.如果这样做,您可以使用 var
在foreach
循环:
var props = TypeDescriptor.GetProperties(adapter).Cast<PropertyDescriptor>();
// No error
foreach (var prop in props)
{
string name = prop.DisplayName;
}
关于c# - var 关键字并不总是有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874072/