如何通过反射从类中发现基-基-基类

本文关键字:发现 基类 何通过 反射 | 更新日期: 2023-09-27 17:54:45

我有以下场景:

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; }
}

好的,现在我将通过反射发现Student类的属性。

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类型?谢谢!

如何通过反射从类中发现基-基-基类

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

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

一旦你有了一个系统。类型对象,您可以迭代地查看'BaseType'属性,直到它为null或它为'BaseEntity'。