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

前端 未结 9 2054
感情败类
感情败类 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:53

    You can loop through all non-indexed properties of an object like this:

    var s = new MyObject();
    foreach (var p in s.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) {
        Console.WriteLine(p.GetValue(s, null));
    }
    

    Since GetProperties() returns indexers as well as simple properties, you need an additional filter before calling GetValue to know that it is safe to pass null as the second parameter.

    You may need to modify the filter further in order to weed out write-only and otherwise inaccessible properties.

提交回复
热议问题