如何使用反射和递归得到任何对象的所有名称和值递归、如何使用、反射、对象

2023-09-06 10:44:45 作者:行走在冷风中

我想从对象的实例获取属性名称和值。我需要它来工作包含嵌套对象的对象在那里我可以简单的通过在父实例。

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.

例如,如果我有:

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

我如何确定该属性是什么,然后传递到PrintProperties?

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

推荐答案

您获得价值已经,试试这个:

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);
}
 
精彩推荐
图片推荐