查看对象的所有属性和值(包括子对象)

时间:2012-11-29 22:10:48

标签: .net reflection properties

我想知道.Net中是否有内置功能可以输出(在运行时)给定对象中的所有属性和值,如果可能,甚至包括子对象。

我正在考虑反思或XML Serializion并看到some people mentioned JSON,但无法真正弄清楚如何以正确的方式做到这一点......有谁知道这是否可能是内置的.Net中的功能,或者是否有一个很好的示例/工具已经可以做到这一点,或者可以指导我朝正确的方向发展?

2 个答案:

答案 0 :(得分:3)

使用Reflection

查看对象的所有公共属性和值:

foreach(var prop in obj.GetType().GetProperties()) //note: you can pass in binding flags to GetProperties to get static, private, etc properties
{
    var propVal = prop.GetValue(obj);

    //prop has information such as Name, PropertyType
    //propVal is the value of that property for obj
}

答案 1 :(得分:1)

您可以使用XmlSerializer课程或查看JSON.Net框架。

相关问题