How can you loop over the properties of a class?

后端 未结 11 1583
温柔的废话
温柔的废话 2020-11-29 23:37

Is there a way in c# to loop over the properties of a class?

Basically I have a class that contains a large number of property\'s (it basically holds the results of

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 00:04

    I tried various recommendations on this page, I couldn't quite get any of them to work. I started with the top answer (you'll notice my variables are similarly named), and just worked through it on my own. This is what I got to work - hopefully it can help someone else.

    var prop = emp.GetType().GetProperties();     //emp is my class
        foreach (var props in prop)
          {
            var variable = props.GetMethod;
    
            empHolder.Add(variable.Invoke(emp, null).ToString());  //empHolder = ArrayList
          }
    

    ***I should mention this will only work if you're using get;set; (public) properties.

提交回复
热议问题