从 IEnumerable<T> 获取类型 T [英] getting type T from IEnumerable&lt;T&gt;

查看:42
本文介绍了从 IEnumerable<T> 获取类型 T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过反射从IEnumerable中检索T类型?

is there a way to retrieve type T from IEnumerable<T> through reflection?

例如

我有一个变量 IEnumerable info;我想通过反射来检索 Child 的类型

i have a variable IEnumerable<Child> info; i want to retrieve Child's type through reflection

推荐答案

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

因此,

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

打印System.String.

请参阅 MSDN 了解 类型.GetGenericArguments.

我相信这将解决评论中的问题:

I believe this will address the concerns in the comments:

// 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,因此有必要返回它们的枚举.

Some objects implement more than one generic IEnumerable so it is necessary to return an enumeration of them.

虽然,我不得不说,一个类为多个T实现IEnumerable是一个糟糕的主意>.

Although, I have to say, it's a terrible idea for a class to implement IEnumerable<T> for more than one T.

这篇关于从 IEnumerable<T> 获取类型 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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