从IEnumerable <T>获取类型T

有没有一种方法来检索类型TIEnumerable<T>通过反射?

例如

我有一个可变的IEnumerable<Child>信息;我想通过反射来检索孩子的类型


慕标5832272
浏览 761回答 3
3回答

幕布斯6054654

我只是做一个扩展方法。这与我投入的所有工作都有效。public static Type GetItemType<T>(this IEnumerable<T> enumerable){&nbsp; &nbsp; return typeof(T);}

人到中年有点甜

我有一个类似的问题。所选答案适用于实际实例。就我而言,我只有一个类型(来自PropertyInfo)。如果类型本身typeof(IEnumerable<T>)不是的实现,则所选答案失败IEnumerable<T>。对于这种情况,以下工作:public static Type GetAnyElementType(Type type){&nbsp; &nbsp;// Type is Array&nbsp; &nbsp;// short-circuit if you expect lots of arrays&nbsp;&nbsp; &nbsp;if (type.IsArray)&nbsp; &nbsp; &nbsp; return type.GetElementType();&nbsp; &nbsp;// type is IEnumerable<T>;&nbsp; &nbsp;if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>))&nbsp; &nbsp; &nbsp; return type.GetGenericArguments()[0];&nbsp; &nbsp;// type implements/extends IEnumerable<T>;&nbsp; &nbsp;var enumType = type.GetInterfaces()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Where(t => t.IsGenericType &&&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t.GetGenericTypeDefinition() == typeof(IEnumerable<>))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Select(t => t.GenericTypeArguments[0]).FirstOrDefault();&nbsp; &nbsp;return enumType ?? type;}
打开App,查看更多内容
随时随地看视频慕课网APP