通过reflectionC#获取嵌套属性值

我有以下代码。

类别:

public class AlloyDock { public int Left { get; set; } public int Right { get; set; } } public class Charger { public int Left { get; set; } public int Right { get; set; } } public class VehicleControlTest { public Charger Charger1 { get; set; } } public class BasicControlTest { public AlloyDock AlloyDock1 { get; set; } } class Appointment { public BasicControlTest BasicControlTest1 { get; set; } public VehicleControlTest VehicleControlTest1 { get; set; } } 

主function:

  var obj = new Appointment(); obj.BasicControlTest1 = new BasicControlTest(); obj.BasicControlTest1.AlloyDock1 = new AlloyDock(); obj.BasicControlTest1.AlloyDock1.Left = 1; obj.BasicControlTest1.AlloyDock1.Right = 2; obj.VehicleControlTest1 = new VehicleControlTest(); obj.VehicleControlTest1.Charger1 = new Charger(); obj.VehicleControlTest1.Charger1.Left = 3; obj.VehicleControlTest1.Charger1.Right = 4; var parentProperties = obj.GetType().GetProperties(); foreach (var prop in parentProperties) { // Get Main objects inside each test type. var mainObjectsProperties = prop.PropertyType.GetProperties(); foreach (var property in mainObjectsProperties) { var leafProperties = property.PropertyType.GetProperties(); foreach (var leafProperty in leafProperties) { Console.WriteLine("{0}={1}", leafProperty.Name, leafProperty.GetValue(obj, null)); } } } 

我想获取叶节点的属性名称和值。 我能够得到名字但是当我试图获得价值时(分别为1,2,3,4)。 我收到了以下错误。

对象与目标类型不匹配。

我只是在试图解决这个问题。 任何人都可以帮助我。

将对象实例传递给GetValue方法时,需要传递正确类型的实例:

 // 1st level properties var parentProperties = obj.GetType().GetProperties(); foreach (var prop in parentProperties) { // get the actual instance of this property var propertyInstance = prop.GetValue(obj, null); // get 2nd level properties var mainObjectsProperties = prop.PropertyType.GetProperties(); foreach (var property in mainObjectsProperties) { // get the actual instance of this 2nd level property var leafInstance = property.GetValue(propertyInstance, null); // 3rd level props var leafProperties = property.PropertyType.GetProperties(); foreach (var leafProperty in leafProperties) { Console.WriteLine("{0}={1}", leafProperty.Name, leafProperty.GetValue(leafInstance, null)); } } } 

您可以递归地执行此操作以简化(概括)整个事情:

 static void DumpObjectTree(object propValue, int level = 0) { if (propValue == null) return; var childProps = propValue.GetType().GetProperties(); foreach (var prop in childProps) { var name = prop.Name; var value = prop.GetValue(propValue, null); // add some left padding to make it look like a tree Console.WriteLine("".PadLeft(level * 4, ' ') + "{0}={1}", name, value); // call again for the child property DumpObjectTree(value, level + 1); } } // usage: DumpObjectTree(obj); 

问题在于这个表达式:

 leafProperty.GetValue(obj, null) 

您正在传递根对象以获取叶属性。 在处理每个属性时,您需要获取其值,然后针对它调用GetValue