c# foreach (property in object)… Is there a simple way of doing this?

前端 未结 9 2048
感情败类
感情败类 2020-11-28 22:10

I have a class containing several properties (all are strings if it makes any difference).
I also have a list, which contains many different instances of the class.

9条回答
  •  情深已故
    2020-11-28 22:48

    Give this a try:

    foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
    {
       // do stuff here
    }
    

    Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

    For instance to resolve all public properties:

    foreach (var propertyInfo in obj.GetType()
                                    .GetProperties(
                                            BindingFlags.Public 
                                            | BindingFlags.Instance))
    {
       // do stuff here
    }
    

    Please let me know whether this works as expected.

提交回复
热议问题