【发布时间】:2016-04-14 19:32:26
【问题描述】:
假设我可以使用反射访问字段的类型:
FieldInfo item;
Type type = item.FieldType;
我想知道type 是否是通用List,我该怎么做?我需要如下的东西,但它不起作用:
if (type == typeof(List<>))
【问题讨论】:
标签: c# .net reflection
假设我可以使用反射访问字段的类型:
FieldInfo item;
Type type = item.FieldType;
我想知道type 是否是通用List,我该怎么做?我需要如下的东西,但它不起作用:
if (type == typeof(List<>))
【问题讨论】:
标签: c# .net reflection
你需要的是:
/// <summary>
/// Determines whether the given <paramref name="type"/> is a generic list
/// </summary>
/// <param name="type">The type to evaluate</param>
/// <returns><c>True</c> if is generic otherwise <c>False</c></returns>
public static bool IsGenericList(this Type type)
{
if (!type.IsGenericType) { return false; }
var typeDef = type.GetGenericTypeDefinition();
if (typeDef == typeof(List<>) || typeDef == typeof(IList<>)) { return true; }
return false;
}
【讨论】:
试试
Type type = item.FieldType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
【讨论】: