How to loop through class properties tree?

2019-06-07 03:25发布

问题:

class ClassA 
{
   public ClassB myProp {get;set;}
}

class ClassB 
{
   public ClassC anotherProp {get;set;}
}

class ClassC 
{
   public string Name {get;set;}
}

I have an object of the ClassA type. How, by the reflection iterate recursively to get ClassC's Name property value ?

回答1:

I was a little sketchy on what you wanted to accomplish. I think you want to start with ClassA and eventually walk through the properties and get to ClassC. To do this you mostly have to understand how to do recursive programming and a small amount of knowledge of Reflection. Here is a modified version of code that I have used in the past, which you can find here.

private void SerializeObject(object obj) {

    Type type = obj.GetType();

    foreach (PropertyInfo info2 in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
    {
        MethodInfo getMethod = info2.GetGetMethod(true);

        if (getMethod != null)
            SerializeObject(getMethod.Invoke(obj, null));
    }

}

What this does is walk through each property and uses the get method of each property to execute the property and get the object that is being returned so that you can walk through it by calling the same SerializeObject method.



回答2:

Ok, solved. Let's say that I have the path to the Property which value I wanna get:

ClassB.ClassC.Name

then, after splitting that parh I iterate through the tree without recursion ;)

var dataPath = column.SortMemberPath.Split(new char[] { '.' });

[...]

foreach (var item in (System.Collections.IList)myObject)
{
   var newItem = item;

   foreach (var path in dataPath)
   {
         var actalValue = newItem.GetType().GetProperty(path).GetValue(newItem, null);
         newItem = actalValue; //it does the trick
   }

   now, the newItem is my wanted property value 
}


标签: c# reflection