如何通过Reflection发现类中的基础基类?

时间:2014-03-29 19:19:16

标签: c# reflection

我有以下情况:

public class BaseEntity { 
    public int Id { get; set; }
}
public class BaseAcademicEntity : BaseEntity { ... }
public class BaseFinancialEntity : BaseEntity { ... }

public class Student : BaseAcademicEntity {
    public string Name { get; set; }
    public Grade CurrentGrade { get; set; }
}
public class Grade : BaseAcademicEntity {
    public string Description { get; set; }
}

好的,现在我将通过Reflection发现Student class的属性。

foreach (PropertyInfo property in typeof(Student).GetProperties()) {

    // Here I can discover the type of the current property.
    var type = property.PropertyType;

    // now, how to discover if this property is from BaseEntity type?
}

就像我在评论中写的那样,如何发现该属性是否来自BaseEntity类型?谢谢!

2 个答案:

答案 0 :(得分:3)

最简单的方法是使用Type.IsAssignableFrom

if (typeof(BaseEntity).IsAssignableFrom(type))

答案 1 :(得分:1)

一旦有了System.Type对象,就可以迭代地查看'BaseType'属性,直到它为null或者它是'BaseEntity'。