首页 > 解决方案 > 检查属性类型是否为 List<> 类型

问题描述

我正在尝试检查一个类的属性是否List<>存在。

我尝试过使用IsAssignableFrom()方法来检查它是否是一个列表。

我也尝试过使用GetInterfaces()方法。

但两个结果都返回错误。

我的课是:

public class Product2 
{
    public List<ProductDetails2> ProductDetails { get; set; }
}

使用方法IsassignableFrom()

var t = typeof(Product2).GetProperties();
foreach(var p in t) 
{
    var isEnumerable = typeof(Enumerable).IsAssignableFrom((p.PropertyType));
}

使用方法GetInterfaces()

var t = typeof(Product2).GetProperties();    
foreach(var p in t) 
{  
    var isEnumerable = parameter.GetType().GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
}

在上述两种情况下,Product2.ProductDetails 属性都为 false。

标签: c#asp.net-mvcentity-framework

解决方案


但是为什么在这种情况下不工作IsAssignableFrom()GetInterfaces()

 var isEnumerable = typeof(Enumerable).IsAssignableFrom((p.PropertyType));

这不起作用,因为Enumerable它是一个包含扩展方法的静态类IEnumerable<T>

您的第二个样本的概念GetInterfaces()似乎是正确的;但是,您使用parameter变量而不是foreach循环变量p,这可能是问题所在。


一旦我为此创建了几个扩展方法

public static bool IsGenericTypeOf(this Type type, Type genericTypeDefinition)
    => type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition;

public static bool IsImplementationOfGenericType(this Type type, Type genericTypeDefinition)
{
    if (!genericTypeDefinition.IsGenericTypeDefinition)
        return false;

    // looking for generic interface implementations
    if (genericTypeDefinition.IsInterface)
    {
        foreach (Type i in type.GetInterfaces())
        {
            if (i.Name == genericTypeDefinition.Name && i.IsGenericTypeOf(genericTypeDefinition))
                return true;
        }

        return false;
    }

    // looking for generic [base] types
    for (Type t = type; type != null; type = type.BaseType)
    {
        if (t.Name == genericTypeDefinition.Name && t.IsGenericTypeOf(genericTypeDefinition))
            return true;
    }

    return false;
}

例子:

public class MyList : List<ProductDetails2> { }

//...

typeof(List<ProductDetails2>).IsGenericTypeOf(List<>); // true
typeof(MyList).IsGenericTypeOf(List<>); // false

typeof(MyList).IsImplementationOfGenericType(List<>); // true
typeof(MyList).IsImplementationOfGenericType(IEnumerable<>); // true

推荐阅读