c# - 为什么 Type.GetElementType 返回 null?

标签 c# reflection

我有一个方法将 IEnumerable 类型的对象作为输入参数.我想枚举枚举并为每个项目使用反射来获取每个属性的值。

我有以下代码:

protected void WriteData(IEnumerable data)
{
    var enumerationTypeInfo = data.GetType();
    var itemTypeInfo = enumerationTypeInfo.GetElementType();

    ...
}

问题是enumerationTypeInfo.GetElementType()总是返回 null .特别是,我传递了一个 List<Entry>进入WriteData , 其中Entry是我创建的一个类。当我使用调试器并设置断点时,我可以看到 enumerationTypeInfo正确显示它是 Entry 类型的列表,但为什么 GetElementType返回 null

谢谢

最佳答案

GetElementType()返回数组的元素类型。 List<T>不是数组类型,因此没有“元素类型”。

如果要随机获取元素类型IEnumerable<T>产生,尝试这样的事情:

public static Type GetEnumerableType(Type type)
{
    if (type == null)
        throw new ArgumentNullException("type");

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        return type.GetGenericArguments()[0];

    var iface = (from i in type.GetInterfaces()
                 where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)
                 select i).FirstOrDefault();

    if (iface == null)
        throw new ArgumentException("Does not represent an enumerable type.", "type");

    return GetEnumerableType(iface);
}

请注意,类型可以实现同一通用接口(interface)的多个版本;一个类型可以同时实现 IEnumerable<int>IEnumerable<string>例如。你如何处理这种情况取决于你。我提供的方法将采用运行时首先交给它的接口(interface)类型。


参见 an example using the above method在 ideone 上。

关于c# - 为什么 Type.GetElementType 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072088/

相关文章:

c# - 无法传递符合泛型约束类型的变量

c# - C#中的字符串操作

java - 动态获取注解值,而不是硬编码类/方法名称来获取注解值

C# MVC Controller 错误地解析来自 POST 的 JSON

java - 我将如何递归地比较两个相同但未知类型的 Java 对象的字段值?

java - 检测何时在 Root设备上接听去电

c# - 如何用代码更新c#中的数据表?

c# - 从 C# 注册自定义 win32 窗口类

c# - 以编程方式和从命令行 (DTEXEC) 运行 SSIS 包时遇到问题

c# - 如何从 Action<T> 获取方法的自定义属性?