Generating Complex Objects with Dynamic Properties Using Reflection Emit at Runtime

72 views Asked by At

So The concept in my head kind of straightforward I'm just unsure how to implement this correctly. I've got a class called Banana and a class Called Dog for simplicity sake. Banana has a Dictionary of <string,Banana> And Dog inherits from banana.

Now lets say i got another class lets call it DynamicClass. this gets generated during runtime with reflection, some of its properties are simple like booleans etc and some are complex like Banana .

You can create a new dog class like this : new Dog(Banana) Now what i need to do is Converts Banana to dog using reflection emit, so yeah i can check against the type of the propery and if its of type Banana i change the type lets say something like this:

`  public object TestMethod(object input)
    {
        Type inputType = input.GetType();
        PropertyInfo[] properties = inputType.GetProperties();

        AssemblyName assemblyName = new AssemblyName("DynamicAssembly");
        AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");

        TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);

        foreach (var prop in properties)
        {
            Type propType = prop.PropertyType;

            if (propType == typeof(Banana))
            {
                propType = typeof(Dog);
            }
         FieldBuilder fieldBuilder = typeBuilder.DefineField("_" + prop.Name.ToLower(), propType,        FieldAttributes.Private);
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(prop.Name, PropertyAttributes.HasDefault, propType, null);`

Now the problem is I must also do this for the inner dictionary and recursively. What i mean by that That i want to go over the inner properties of Banana and
find if one of them is of type Dictionary<string,Banana> and tell the propType to now be equal to Dictionary<string,Dog>.

In addition i want to fill them with the fill them with the values from the previous Dictionary Something in the form of new Dog(Banana) While looping over the KeyValuePair. This also needs to happen recursively because those Bananas can contain more dictionaries, and in a different methode as to not overwrite the proprType and the propBuilder etc.. . How can i implement this?

This is the full code if anybody cares to see: codeshare (Gives me access is denied error) This is a full example u can run this.

Tried Everything i had in mind before posting this Another edit: link changed

0

There are 0 answers