如何检测类型是否为列表

本文关键字:类型 是否 列表 检测 何检测 | 更新日期: 2023-09-27 18:29:37

假设我可以使用反射访问字段的类型:

FieldInfo item;
Type type = item.FieldType;

我想知道type是否是通用List,我该怎么做?我需要如下的东西,但它不起作用:

if (type == typeof(List<>))

如何检测类型是否为列表

尝试

Type type = item.FieldType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))

您需要的是:

/// <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;
}