reflection on List and printing values

前端 未结 6 878
眼角桃花
眼角桃花 2020-12-20 18:31

I wrote a method that accepts a generic parameter and then it prints its properties. I use it to test my web service. It\'s working but I want to add some features that I do

6条回答
  •  旧时难觅i
    2020-12-20 19:05

    Borrowing heavily on the above examples, here is my full solution. This has been tested and handles IEnumerable's being passed in by printing out the properties of each element. It's not recursive but that's easy enough to add.

    Be aware that many of the above examples will crash with indexed properties (lists for example). Parameter count mismatch in property.GetValue().

    It's avoided here by filtering properties which have indexed properties using this bit of LINQ.

    Where(x=>!x.GetIndexParameters().Any())
    

    Full example in the form of an extension method below.

        /// 
        /// Returns string representation of object property states i.e. Name: Jim, Age: 43
        /// 
        public static string GetPropertyStateList(this object obj)
        {
            if (obj == null) return "Object null";
    
            var sb = new StringBuilder();
            var enumerable = obj as IEnumerable;
    
            if (enumerable != null)
            {
                foreach (var listitem in enumerable)
                {
                    sb.AppendLine();
                    sb.Append(ReadProperties(listitem));
                }
            }
            else
            {
                sb.Append(ReadProperties(obj));
            }
    
            return sb.ToString();
        }
    
        private static string ReadProperties(object obj)
        {
            var sb = new StringBuilder();
            var propertyInfos = obj.GetType().GetProperties().OrderBy(x => x.Name).Where(x=>!x.GetIndexParameters().Any());
    
            foreach (var prop in propertyInfos)
            {
                var value = prop.GetValue(obj, null) ?? "(null)";
                sb.AppendLine(prop.Name + ": " + value);
            }
    
            return sb.ToString();
        }
    

提交回复
热议问题