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

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

    A copy-paste solution (extension methods) mostly based on earlier responses to this question.

    Also properly handles IDicitonary (ExpandoObject/dynamic) which is often needed when dealing with this reflected stuff.

    Not recommended for use in tight loops and other hot paths. In those cases you're gonna need some caching/IL emit/expression tree compilation.

        public static IEnumerable<(string Name, object Value)> GetProperties(this object src)
        {
            if (src is IDictionary dictionary)
            {
                return dictionary.Select(x => (x.Key, x.Value));
            }
            return src.GetObjectProperties().Select(x => (x.Name, x.GetValue(src)));
        }
    
        public static IEnumerable GetObjectProperties(this object src)
        {
            return src.GetType()
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => !p.GetGetMethod().GetParameters().Any());
        }
    

提交回复
热议问题