【问题标题】:How to detect if a Type is a List? [duplicate]如何检测类型是否为列表? [复制]
【发布时间】:2016-04-14 19:32:26
【问题描述】:

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

FieldInfo item;
Type type = item.FieldType;

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

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

【问题讨论】:

    标签: c# .net reflection


    【解决方案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;
    }
    

    【讨论】:

      【解决方案2】:

      试试

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

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 2019-01-05
        • 1970-01-01
        • 2011-07-22
        • 2021-08-03
        • 1970-01-01
        • 2012-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多