且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 IEnumerable 获取类型 T

更新时间:2023-02-14 10:56:01

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.