好的,我正在尝试使用反射来遍历一个类以获取该类和子类的所有属性和值。我遇到的问题是获取一个类的值,该类是我正在使用的对象的子类。例如。我想在下面的示例中获取 Teacher 对象的 ClassRoom 属性。
我遇到的另一个问题是如何确定何时到达可包含的属性,例如学生列表,这样我就可以让它遍历列表。
前任:
public class Teacher
{
public int ID {get;set;}
public string FullName {get;set;}
public ClassRoom HomeRoom {get;set;}
public List<Student> Students {get;set;}
}
public class ClassRoom
{
public int ID {get;set;}
public string RoomNumber {get;set;}
}
public class Student
{
public int ID {get;set;}
public string FullName {get;set;}
}
private void LoadTeacher()
{
Teacher thisTeacher = Session["Teacher"] as Teacher;
Type type = thisTeacher.GetType();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
{
Type headerType = prop.PropertyType;
PropertyInfo[] headerProps = headerType.GetProperties();
//Instantiate an object of the headerType
object headerObj = Activator.CreateInstance(headerType);
foreach (PropertyInfo childProp in headerProps)
{
if (!childProp.PropertyType.IsClass || childProp.PropertyType == typeof(string))
{
//This object always get loaded with default values, Why?
object value = childProp.GetValue(headerObj, null);
}
}
}
}
}