2014-03-29 49 views
0

我有以下情形:如何通過反射從類中發現基類基類?

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

好了,現在我會通過反思發現從學生類的屬性。

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類型?謝謝!

回答

3

最簡單的方法是使用Type.IsAssignableFrom

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

謝謝。它像一個魅力! – Kiwanax

1

一旦你有一個System.Type對象,你可以反覆看「BASETYPE」屬性,直到它爲空或它的「BaseEntity」。

+0

我已經這樣做了。它工作,但我想要一個更優雅的解決方案。 – Kiwanax

+1

我認爲喬恩的解決方案更加優雅(希望我能想到它)。 –