How to get all names and values of any object using reflection and recursion

心已入冬 提交于 2020-01-25 05:39:03

问题


I am trying to get a property names and values from an instance of an object. I need it to work for objects that contain nested objects where I can simple pass in the the parent instance.

For example, if I have:

public class ParentObject
{
    public string ParentName { get; set; }
    public NestedObject Nested { get; set; }
}

public class NestedObject
{
    public string NestedName { get; set; }
}

 // in main
 var parent = new ParentObject();
 parent.ParentName = "parent";
 parent.Nested = new NestedObject { NestedName = "nested" };                                   

 PrintProperties(parent); 

I have attempted a recursive method:

public static void PrintProperties(object obj)
{
     var type = obj.GetType();

     foreach (PropertyInfo p in type.GetProperties())
     {
         Console.WriteLine(p.Name + ":- " + p.GetValue(obj, null));

         if (p.PropertyType.GetProperties().Count() > 0)
         {              
             // what to pass in to recursive method
             PrintProperties();                                       
          }
        }

        Console.ReadKey();
    }

How do I determine that the property is then what is passed in to the PrintProperties?


回答1:


You get the value already, try this:

object propertyValue = p.GetValue(obj, null);
Console.WriteLine(p.Name + ":- " + propertyValue);

if (p.PropertyType.GetProperties().Count() > 0)
{              
    // what to pass in to recursive method
    PrintProperties(propertyValue);
}


来源:https://stackoverflow.com/questions/26712142/how-to-get-all-names-and-values-of-any-object-using-reflection-and-recursion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!