【问题标题】:Iterate through class properties to get child class values遍历类属性以获取子类值
【发布时间】:2012-07-28 02:24:51
【问题描述】:

好的,我正在尝试使用反射来遍历一个类以获取该类和子类的所有属性和值。我遇到的问题是获取一个类的值,该类是我正在使用的对象的子类。例如。我想在下面的示例中获取 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);                                                    
                }
            }
        }
    }
}

【问题讨论】:

  • 是的,我意识到这个测试 (prop.PropertyType.IsClass && prop.PropertyType != typeof(string)) 不是万无一失的,非常感谢任何建议。

标签: .net reflection


【解决方案1】:
   var teacher = new Teacher()
    {
      HomeRoom = new ClassRoom { ID = 12, RoomNumber = "7-1" },
      Students = new List<Student> { new Student{ID =1, FullName = "Smith1"}, new Student{ID=2, FullName = "Smith2"} }
    };
    Console.WriteLine("Teacher");
    Browse(teacher, 1);

 static void Browse(object item, int level = 0)
  {
    if (item == null)
      return;
    var prefix = new string(' ', level * 2);

    var type = item.GetType();
    foreach (var prop in type.GetProperties())
    {
      var value = prop.GetValue(item, null);
      if (value is System.Collections.IEnumerable && !(value is string))
      {
        Console.WriteLine("{0}{1}", prefix, prop.Name);
        foreach (var index_entry in ((System.Collections.IEnumerable)value).OfType<object>().Select((entry, index) => new { entry, index }))
        {
          Console.WriteLine("{0}[{1}]: {2}", prefix, index_entry.index, index_entry.entry);
          Browse(index_entry.entry, level + 1);
        }
      }
      else if (value != null && !value.GetType().IsPrimitive && !(value is string))
      {
        Console.WriteLine("{0}{1}: {2}", prefix, prop.Name, value);
        Browse(value, level + 1);
      }
      else
      {
        Console.WriteLine("{0}{1}: {2}", prefix, prop.Name, value);
      }

    }
  }

输出

Teacher
  ID: 0
  FullName:
  HomeRoom: Program+ClassRoom
    ID: 12
    RoomNumber: 7-1
  Students
  [0]: Program+Student
    ID: 1
    FullName: Smith1
  [1]: Program+Student
    ID: 2
    FullName: Smith2

【讨论】:

  • 这很好用,不知道我怎么忽略了它。谢谢。问题仍然存在,您如何确定您正在查看的属性是否是可包含的(列表、数组等),以便您可以获取该对象并对其进行迭代。
  • 新答案看起来很棒。我会在这里尝试一下。谢谢!
猜你喜欢
  • 2011-06-30
  • 2012-10-29
  • 2013-04-25
  • 2011-12-30
  • 2013-07-05
  • 1970-01-01
  • 2010-10-26
  • 2012-07-05
  • 1970-01-01
相关资源
最近更新 更多