mercredi 21 août 2019

How to initialize a List

TL;DR
I'm stuck with initializing my List<T>s and elements using reflection.

Description
I'm trying to initialize my whole export class programmatically using reflection.
This class contains a lot sub classes and lists.

The purpose of this function is to quickly generate a filled class for XML export.
And why am I using reflection, you may ask, that's because of the fact that I have a lot of different classes of the huge kind.
It would be a pain in the ass to write them all out just for testing purpose.

Code

public static object Populate(object object_Orginal)
{
    PropertyInfo[] PropertyInfos = object_Orginal.GetType().GetProperties();

    for (int iIndex = 0; iIndex < PropertyInfos.Length; iIndex++)
    {
        PropertyInfo PropertyInfo_Tmp = PropertyInfos[iIndex];

        if (PropertyInfo_Tmp.GetSetMethod() == null)
        {
            continue;
        }
        // Is it right to exclude them?
        if (PropertyInfo_Tmp.Name == "Capacity" || PropertyInfo_Tmp.Name == "Count")
        {
            continue;
        }
        Type Type_Tmp = PropertyInfo_Tmp.PropertyType;

        if (Type_Tmp == typeof(int))
        {
            PropertyInfo_Tmp.SetValue(object_Orginal, 1);
        }
        // [...] a few more basic types

        // >>> Here I'm completly stuck - and yea it's a mess
        else if (Type_Tmp.Name == "List`1") // typeof(List<>))
        {
            object list = Activator.CreateInstance(Type_Tmp);

            MethodInfo add = Type_Tmp.GetMethod("Add");

            IEnumerable<Attribute> a = PropertyInfo_Tmp.GetCustomAttributes();

            PropertyInfo[] propertyInfo = list.GetType().GetProperties();
            foreach (PropertyInfo property in propertyInfo)
            {
                object d = Populate(property);
                property.SetValue(list, d);
            }

            //foreach (Attribute item in a)
            //{
            //    add.Invoke(list, new object[] { Populate(item) });
            //}

            //add.Invoke(list, new[] { item });
            //prop.SetValue(x, list, null); 

        }
        // <<<

        else
        {
            ConstructorInfo ConstructorInfo_Property = Type_Tmp.GetConstructor(Type.EmptyTypes);
            object object_Property = ConstructorInfo_Property.Invoke(new object[0]);
            object_Property = Populate(object_Property);
            PropertyInfo_Tmp.SetValue(object_Orginal, object_Property);
        }
    }
    return object_Orginal;
}

Original code from here

I tried a few different ways but can't implement them right.
The primary goal is to initialize the List<T> and then add one - more items to the list and initialize them recursively.





Aucun commentaire:

Enregistrer un commentaire