开发者

C# Reflection and Getting Properties

I have the following dummy class structure and I am trying to find out how to get the properties from each instance of the class People in PeopleList. I know how to get the properties from a single instance of People but can't for the life of me figure out how to get it from PeopleList. I am sure t开发者_如何学运维his is really straightforward but can someone point me in the right direction?

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


Still not 100% sure of what you want, but this quick bit of code (untested) might get you on the right track (or at least help clarify what you want).

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# should be able to work out that 'PeopleList' inherits from 'List' and handle that fine, but if you need to have 'PeopleList' as the generic type, then this should work:

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

Note that this will actually process properties in derived types within the list as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜