reflection on List and printing values

前端 未结 6 913
眼角桃花
眼角桃花 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条回答
  •  一个人的身影
    2020-12-20 19:19

    You could do something like this:

        static void printReturnedProperties(Object o)
        {
            PropertyInfo[] propertyInfos = null;
            propertyInfos = o.GetType().GetProperties();
    
    
    
            foreach (var item in propertyInfos)
            {
                var prop = item.GetValue(o);
    
                if(prop == null)
                {
                    Console.WriteLine(item.Name + ": NULL");
                }
                else
                {
                    Console.WriteLine(item.Name + ": " + prop.ToString());
                }
    
    
                if (prop is IEnumerable)
                {
                    foreach (var listitem in prop as IEnumerable)
                    {
                        Console.WriteLine("Item: " + listitem.ToString());
                    }
                }
            }
    
    
        }
    

    It will then enumerate through any IEnumerable and print out the individual values (I'm printing them one per line, but obviously, you can do different.)

提交回复
热议问题