lundi 30 avril 2018

Get all properties and subproperties from a class

I am using reflection to get a class name, and need to get all sub properties of the class, and all the sub properties' properties.

I am running into a recursion issue where the items get added to the incorrect list.

My code is as follows:

private List<Member> GetMembers(object instance)
        {
            var memberList = new List<Member>();
            var childMembers = new List<Member>();

            foreach (var propertyInfo in instance.GetType().GetProperties())
            {
                var member = new Member
                {
                    Name = propertyInfo.PropertyType.IsList() ? propertyInfo.Name + "[]" : propertyInfo.Name,
                    Type = SetPropertyType(propertyInfo.PropertyType),
                };

                if (propertyInfo.PropertyType.IsEnum)
                {
                    member.Members = GetEnumValues(propertyInfo).ToArray();
                }

                if (propertyInfo.PropertyType.BaseType == typeof(ModelBase))
                {
                    var childInstance = propertyInfo.GetValue(instance) ?? Activator.CreateInstance(propertyInfo.PropertyType);

                    childMembers.AddRange(GetMembers(childInstance));

                    member.Members = childMembers.ToArray();
                }

                if (propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                    propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
                {
                    var itemType = propertyInfo.PropertyType.GetGenericArguments()[0];

                    var childInstance = Activator.CreateInstance(itemType);

                    childMembers.AddRange(GetMembers(childInstance));

                    member.Members = childMembers.Distinct().ToArray();
                }

                memberList.Add(member);
            }

            return memberList;
        }





Aucun commentaire:

Enregistrer un commentaire