如何递归使用反射对象的属性值 [英] How to recursively print the values of an object's properties using reflection

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

问题描述

为了帮助调试一些code我的工作,我开始写递归地打印出一个对象的属性的名称和值的方法。但是,大部分对象包含嵌套类型,我想打印他们的名字和值太多,但只在我的类型定义。

To aid in debugging some code I'm working on, I started to write a method to recursively print out the names and values of an object's properties. However, most of the objects contain nested types and I'd like to print their names and values too, but only on the types I have defined.

下面是什么,我至今大纲:

Here's an outline of what I have so far:

public void PrintProperties(object obj)
{
    if (obj == null)
        return;

    Propertyinfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if ([property is a type I have defined])
        {
            PrintProperties([instance of property's type]);
        }
        else
        {
            Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
        }
    }

括号中的部分在哪里我不确定。

The parts between the braces are where I'm unsure.

任何帮助将大大AP preciated。

Any help will be greatly appreciated.

推荐答案

下code的那个企图。对于类型的我已经定义了我选择看类型相同的组件,正在打印其属性的类型的人,但你需要更新逻辑,如果你的类型在多个组件定义。

The code below has an attempt at that. For "type I have defined" I chose to look at the types in the same assembly as the ones the type whose properties are being printed, but you'll need to update the logic if your types are defined in multiple assemblies.

public void PrintProperties(object obj)
{
    PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
    if (obj == null) return;
    string indentString = new string(' ', indent);
    Type objType = obj.GetType();
    PropertyInfo[] properties = objType.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        object propValue = property.GetValue(obj, null);
        if (property.PropertyType.Assembly == objType.Assembly && !property.PropertyType.IsEnum)
        {
            Console.WriteLine("{0}{1}:", indentString, property.Name);
            PrintProperties(propValue, indent + 2);
        }
        else
        {
            Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
        }
    }
}

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

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