为什么 Type.GetElementType 返回 null? [英] Why does Type.GetElementType return null?
问题描述
我有一个方法将 IEnumerable
类型的对象作为输入参数.我想枚举枚举,并为每个项目使用反射来获取每个属性的值.
I have a method that takes as an input parameter an object of type IEnumerable
. I want to enumerate the enumeration and for each item use reflection to get the value for each property.
我有以下代码:
protected void WriteData(IEnumerable data)
{
var enumerationTypeInfo = data.GetType();
var itemTypeInfo = enumerationTypeInfo.GetElementType();
...
}
问题是enumerationTypeInfo.GetElementType()
总是返回null
.特别是,我将一个 List
传入 WriteData
,其中 Entry
是我创建的一个类.当我使用调试器并设置断点时,我可以看到 enumerationTypeInfo
正确显示它是 Entry
类型的列表,但是为什么 GetElementType
返回null
?
The problem is enumerationTypeInfo.GetElementType()
always returns null
. In particular, I'm passing in a List<Entry>
into WriteData
, where Entry
is a class I created. When I use the debugger and set a breakpoint I can see that enumerationTypeInfo
correctly shows that it's a List of type Entry
, but why does GetElementType
return null
?
谢谢
推荐答案
GetElementType
用于数组,而不是其他通用类.要获取泛型类型的泛型参数,您可以使用 Type.GetGenericArguments
.
GetElementType
is for use with arrays, not other generic classes. To get a generic type's generic parameters, you can use Type.GetGenericArguments
.
这篇关于为什么 Type.GetElementType 返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!