vendredi 13 décembre 2019

Use Reflection to generate 2 generic parent classes and 2 child classes that are dependent upon each other

I want to use reflection to generate 2 classes from 2 generics. The 2 classes to be generated are dependent upon each other as parameters to the 2 generic parents.

this example uses two generic classes:

    Data.Row<T,TABLE_TYPE>
    Data.Table<T, ROW_TYPE>

After generating AssemblyBuilder and ModuleBuilder, I load two type builders.

    TypeBuilder rowTypeBuilder = moduleBuilder.DefineType("MachineData." + dataTypeName + "Row",
               TypeAttributes.Public |
               TypeAttributes.Class |
               TypeAttributes.AutoClass |
               TypeAttributes.AnsiClass |
               TypeAttributes.BeforeFieldInit |
               TypeAttributes.AutoLayout,
               null);
    TypeBuilder tableTypeBuilder = moduleBuilder.DefineType("MachineData." + dataTypeName + "Table",
               TypeAttributes.Public |
               TypeAttributes.Class |
               TypeAttributes.AutoClass |
               TypeAttributes.AnsiClass |
               TypeAttributes.BeforeFieldInit |
               TypeAttributes.AutoLayout,
               null);

I then create the generic parent types

     Type rowParentType = typeof(Data.Row<,>).MakeGenericType(dataType, tableTypeBuilder);
     Type tableParentType = typeof(Data.Table<,>).MakeGenericType(dataType, rowTypeBuilder);

If I set the parents, as below, I get an exception when calling 'CreateType'

        rowTypeBuilder.SetParent(rowParentType);
        tableTypeBuilder.SetParent(tableParentType);
        // DefineConstructor code removed for clarity
        rowTypeBuilder.CreateType();
        tableTypeBuilder.CreateType();

I have tried TypeResolver to both save and load the assembly as well attempting to Create the dependent class in the resolver event handler.

I'm stuck. I was hoping reflection might be a better option than T4 templates or handwriting the code. It creates the assembly quickly and is easy to debug compared with T4 templates.





Aucun commentaire:

Enregistrer un commentaire