How to get all names and values of any object usin

2019-08-02 20:34发布

问题:

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);
}