检查属性类型是否为List <>类型

时间:2019-07-19 06:23:26

标签: c# asp.net-mvc entity-framework

我正在尝试检查类的属性是否为List<>

我尝试使用IsAssignableFrom()方法检查它是否为列表。

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

但是两个结果都返回false。

我的课是:

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。

1 个答案:

答案 0 :(得分:0)

  

但是在这种情况下为何IsAssignableFrom()GetInterfaces()无法正常工作?

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

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

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


一旦我为此创建了couple of extension methods

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
相关问题