mardi 19 juin 2018

Using reflection for inner class

i'm currently using reflection for setting up instances of specified class. I was wondering if it was possible to apply this method to the following kind of class

namespace tmp {
      public class myClass
        {
            public class InnerClass
            {
                public int I { get; set; }
                public int B { get; set; }
            }
            public string Prop1 { get; set; }
            public Test Prop2 { get; set; }
        }
    }
}

So I tried to obtain the properties for the type 'myClass'

            Type type = Type.GetType("tmp.myClass");
            object objInstance = Activator.CreateInstance(type);
            PropertyInfo[] properties = type.GetProperties();
            myClass obj = Activator.CreateInstance(type);

Now , the array 'properties' will have the first element of the type PropertyInfo, that i can use for assigning a value to the instance obj

properties[0].SetValue(obj,"MyString");

But then, i'm not able to do the same thing with the property Prop2, in fact the second element of properties is of the type System.Reflection.RuntimePropertyInfo, so I can't find a way for editing its value.

As now, I tried using the following method

        Type type1 = Type.GetType("tmp.myClass");
        Type type2 = Type.GetType("tmp.myClass.InnerClass");
        var obj = Activator.CreateInstance(type1);
        var obj2 = Activator.CreateInstance(type2);

        PropertyInfo[] properties = type1.GetProperties();
        properties[1].SetValue(obj, obj2);

But when creating the instance of type2 , System.ArgumentNullException gets thrown.

Thank you.





Aucun commentaire:

Enregistrer un commentaire