c# - 从 IEnumerable<T> 获取类型 T

标签 c# generics reflection

有没有办法检索类型 T来自 IEnumerable<T>通过反射(reflection)?

例如

我有一个变量 IEnumerable<Child>信息;我想通过反射获取 Child 的类型

最佳答案

IEnumerable<T> myEnumerable;
Type type = myEnumerable.GetType().GetGenericArguments()[0]; 

因此,

IEnumerable<string> strings = new List<string>();
Console.WriteLine(strings.GetType().GetGenericArguments()[0]);

打印 System.String .

参见 MSDN对于 Type.GetGenericArguments .

编辑:我相信这会解决评论中的问题:

// returns an enumeration of T where o : IEnumerable<T>
public IEnumerable<Type> GetGenericIEnumerables(object o) {
    return o.GetType()
            .GetInterfaces()
            .Where(t => t.IsGenericType
                && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            .Select(t => t.GetGenericArguments()[0]);
}

一些对象实现了多个泛型 IEnumerable因此有必要返回它们的枚举。

编辑:虽然,我不得不说,一个类实现IEnumerable<T> 是一个糟糕的主意。不止一个T .

关于c# - 从 IEnumerable<T> 获取类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906499/

相关文章:

c# - 使用反射确定 .Net 类型在内存中的布局方式

C# 调用 mysql sp 过程不正确的整数值

c# - 编译器在传递方法时无法确定泛型类型

c# - 如何在编译时获得通用参数类型名称?

java - 使用 Mockito 模拟泛型类型时出现 ClassCastException

c# - Roslyn - 查找对具有调用详细信息的方法的所有引用(具体的通用参数)

pointers - 从作为接口(interface)传递的指针连接 slice

c# - Silverlight 中的配置文件

c# - 删除 "[ ]"和字符串中出现的所有内容

c# - asp.net 5.0 project.json 中 RavenDB.Client 引用的问题