如何使用反射递归打印对象属性的值

时间:2011-06-01 04:51:02

标签: c# reflection

为了帮助调试我正在处理的一些代码,我开始编写一个方法来递归地打印出对象属性的名称和值。但是,大多数对象都包含嵌套类型,我也想打印它们的名称和值,但仅限于我定义的类型。

以下是我到目前为止的概述:

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

大括号之间的部分是我不确定的地方。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:26)

下面的代码尝试了这一点。对于“类型I已定义”,我选择查看同一程序集中的类型与正在打印其属性的类型,但如果您的类型在多个程序集中定义,则需要更新逻辑。

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

答案 1 :(得分:8)

你有什么特别的理由要使用反射吗? 相反,你可以像这样使用JavaScriptSerializer

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(obj);
Console.WriteLine(json);

它将递归地包含string中的所有属性,并在出现循环引用的情况下抛出异常。

答案 2 :(得分:1)

Leonid's answer开始,以下代码是我用来创建任何对象的可读Json转储的代码。它忽略空字段并添加缩进以获得更好的视图(特别适用于SOAP对象)。

public static string SerializeToLogJson(this object obj)
        {
            try
            {
                var json = JsonConvert.SerializeObject(obj,
                    Newtonsoft.Json.Formatting.None, 
                    new JsonSerializerSettings { 
                        NullValueHandling = NullValueHandling.Ignore,
                        Formatting = Formatting.Indented
                    });
                return json;
            }
            catch (Exception e)
            {
                log.ErrorFormat(e.Message, e);
                return "Cannot serialize: " + e.Message;
            }
        }

答案 3 :(得分:0)

Newtonsoft库提供了非常简单的函数来将任何对象序列化为JSON。这是一个更简单的解决方案。

Newtonsoft.Json.JsonConvert.SerializeObject(objToSerialize);

例如:

dynamic obj = new { x = 1, y = 2, z = "abc" };
string json = JsonConvert.SerializeObject(obj);
//'json' string value: {"x":1,"y":2,"z":"abc"}