假设我可以使用反射访问字段类型:
FieldInfo item;
Type type = item.FieldType;
我想知道type
是否是通用List
,我该怎么做?我需要如下所示的东西,但它不起作用:
if (type == typeof(List<>))
答案 0 :(得分:1)
尝试
Type type = item.FieldType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
答案 1 :(得分:1)
您需要的是:
/// <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;
}