为什么 Type.GetElementType 返回 null? [英] Why does Type.GetElementType return null?

查看:36
本文介绍了为什么 Type.GetElementType 返回 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屋!

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