Get nested property values through reflection C#

后端 未结 2 1958
梦谈多话
梦谈多话 2020-12-21 19:31

I have following code.

Classes:

public class AlloyDock
{
    public int Left { get; set; }
    public int Right { get; set; }
}

pub         


        
相关标签:
2条回答
  • 2020-12-21 20:07

    When passing an object instance to the GetValue method, you need to pass the instance of the correct type:

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

    You might do this recursively to simplify (generalize) the whole thing:

    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);
    
    0 讨论(0)
  • 2020-12-21 20:32

    The problem is with this expression:

    leafProperty.GetValue(obj, null)
    

    You are passing the root object in to get the leaf property. As you process each property you need to get its value and then call GetValue against it.

    0 讨论(0)
提交回复
热议问题