【发布时间】:2014-11-03 10:22:48
【问题描述】:
我正在尝试从对象的实例中获取属性名称和值。我需要它来处理包含嵌套对象的对象,在这些对象中我可以简单地传入父实例。
例如,如果我有:
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);
我尝试了递归方法:
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 的内容?
【问题讨论】:
-
在调用“GetProperties”之前,您可能应该检查类型(它是一个类吗?)以确保 GetProperties 是相关的。要获取值,请在每个上调用 p.GetValue(obj),并将其与“p”一起传递给“PrintProperty”方法。
标签: c# .net reflection