如何使用反射和递归得到任何对象的所有名称和值 [英] How to get all names and values of any object using reflection and recursion

查看:988
本文介绍了如何使用反射和递归得到任何对象的所有名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何使用反射和递归得到任何对象的所有名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆