C#反射和获取属性

时间:2010-05-04 02:56:01

标签: c# reflection properties

我有以下虚拟类结构,我试图找出如何从PeopleList中的类People的每个实例获取属性。我知道如何从People的单个实例中获取属性,但在我的生活中不能知道如何从PeopleList获取它。我确信这很简单,但是有人能指出我正确的方向吗?

public class Example
{
    public class People
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _age;
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public People()
        {

        }

        public People(string name, int age)
        {
            this._name = name;
            this._age = age;
        }
    }

    public class PeopleList : List<People>
    {
        public static void DoStuff()
        {
             PeopleList newList = new PeopleList();

            // Do some stuff

             newList.Add(new People("Tim", 35));
        }
    }        
}

1 个答案:

答案 0 :(得分:28)

仍然不能100%确定你想要什么,但是这一段代码(未经测试)可能会让你走上正轨(或至少帮助澄清你想要的东西)。

void ReportValue(String propName, Object propValue);

void ReadList<T>(List<T> list)
{
  var props = typeof(T).GetProperties();
  foreach(T item in list)
  {
    foreach(var prop in props)
    {
      ReportValue(prop.Name, prop.GetValue(item));
    }
  }
}

c#应该能够解决'PeopleList'从'List'继承而且处理得很好,但是如果你需要'PeopleList'作为泛型类型,那么这应该有效:

void ReadList<T>(T list) where T : System.Collections.IList
{
  foreach (Object item in list)
  {
    var props = item.GetType().GetProperties();
    foreach (var prop in props)
    {
      ReportValue(prop.Name, prop.GetValue(item, null));
    }
  }
}

请注意,这实际上也会处理列表中派生类型的属性。