Dynamically create type and call constructor of base-class

后端 未结 2 1851
谎友^
谎友^ 2021-01-01 23:52

I need to create a class dynamically. Most things work fine but i\'m stuck in generating the constructor.

AssemblyBuilder _assemblyBuilder =
        AppDomai         


        
相关标签:
2条回答
  • 2021-01-02 00:19

    I think the problem is that you're trying to call the constructor of the open generic type GenericType<GT, TEventSource, TEventArgs>, but you need to call the constructor of the closed type BaseClass<MyType, ConcreteSourceType, ConcreteEventArgsType>. The solution to the seems simple:

    var baseCtor = baseType.GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance, null,
        new[] { typeof(string) }, null);
    

    The problem is that this doesn't work and throws NotSupportedException. So, it seems getting the constructor of a generic type, where one of the parameters is a TypeBuilder is nut supported.

    Because of that, I think what you want is not possible using Reflection.Emit, unless there is some hack to work around this.

    EDIT: A-HA! I had to dive deep into Reflection.Emit in Reflector (although looking at the right place in the documentation would have worked too), but I found it: there is a special method exactly for this: the static TypeBuilder.GetConstructor(). So this should work:

    var baseNonGenericCtor = baseNotGenericType.GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance, null,
        new[] { typeof(string) }, null);
    var baseCtor = TypeBuilder.GetConstructor(baseType, baseNonGenericCtor);
    
    0 讨论(0)
  • 2021-01-02 00:29

    The easiest way to do this would be to compile up your abstract and derived classes into a simple assembly, then open them in Reflector using the "Reflection.Emit" language available as a addin from:

    http://reflectoraddins.codeplex.com/

    Reflector: Reflection.Emit language

    Yes, that's as cool as it sounds :)

    0 讨论(0)
提交回复
热议问题