如何知道属性是否为List <myclass>类型?

时间:2018-07-03 07:03:04

标签: c# reflection collections

我在这些班级都有这个。

public class MyClass:BaseClass
{ }

public class BaseClass
{ }

public class CollectionClass
{
   public string SomeProperty {get; set;}

   public List<MyClass> Collection {get; set;}
}

在我的代码中,我想确定某个对象(例如CollectionClass)中的属性是否为List<BaseClass>的类型,如果属性为{{1 }}。下面的代码对此进行了解释。

List<MyClass>

1 个答案:

答案 0 :(得分:2)

您需要检查封闭类型是否为List<>。可以这样做:

if(property.PropertyType.IsGenericType
    && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))

,然后您必须检查泛型参数(T的{​​{1}}部分)是否可分配给您的基本类型:

List<T>

将它们放在一起,您会得到:

if (typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))

请注意,如注释中所述,即使public bool ContainsMyCollection(object obj) { foreach(var property in obj.GetType().GetProperties()) { // Idk how to accomplish that if(property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>) && typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0])) { return true; } } return false; } 源自List<MyClass>,也不是List<BaseClass>派生的。因此,例如,MyClass将失败。那超出了您的问题范围,但是我想如果您不知道的话,我会提请您注意。