dimanche 20 mars 2022

Getting fields and properties' names, types and values recursively in C#

I am trying to recursively iterate over one root class to grab it's values and build a tree structure for visualization.

For this I have a class that can be initialized with an object

public Item(object genericObject, int depth = 0) {

            this.depth = depth;
            this.Name = genericObject.GetType().Name;
            this.Type = genericObject.GetType().ToString();
            this.Value = genericObject;
            this.subItems = new List<Item>();
            foreach (MemberInfo member in Item.GetType().GetMembers())
            {
                if (member.MemberType != MemberTypes.Method && member.MemberType != MemberTypes.Constructor)
                subItems.Add(new Item(member,genericObject, depth + 1));
            }
        }

and another constructor for recursion

public Item(MemberInfo member,object parentobj, int depth = 0)
        {
            if (member.MemberType == MemberTypes.Property)
            {
                this.FieldName = ((PropertyInfo)member).Name;
                this.FieldType = ((PropertyInfo)member).PropertyType.ToString();
                this.fieldValue = ((PropertyInfo)member).GetValue(parentobj);
            }
            else
            {
                this.FieldName = ((FieldInfo)member).Name;
                this.FieldType = ((FieldInfo)member).GetValue(parentobj).GetType().Name;
                this.fieldValue = ((FieldInfo)member).GetValue(parentobj);
            } 
            switch (member)
            {
                case PropertyInfo propertyInfo:
                case FieldInfo fieldinfo:
                    bool found = false;
                    foreach (string typename in browsethroughtheseTypes)
                    {
                        if (this.FieldType.ToLower().Contains(typename)) found = true;
                    }
                    if (found)
                    {
                        this.subItems = new List<Displayable>();
                       
                        foreach (MemberInfo mem in member.GetType().GetMembers())
                        {
                            if (mem.GetType().IsClass)
                                this.subItems.Add(new Item(mem, depth + 1));
                        }
                    }
                    break;
                default:
                    break;
            }
        }

For testing I only added list to browsethroughthesetypes After recursion takes place in the second constructor all I'm seeing is the internal types. Is there a proper way to achieve this using reflection?





Aucun commentaire:

Enregistrer un commentaire