Is there a way to build a new type during Runtime?

前端 未结 4 1106
[愿得一人]
[愿得一人] 2020-12-28 15:47

I am going to ask a question that might sound weird.

Is there a way to build a new class during Runtime? Or at least, add a new property to an existing class.

<
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 16:26

    Adding a property to an existing type is not possible, but you can create a new type at runtime using Reflection.Emit. It's pretty complicated stuff, and it goes something like this:

    AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
          assemblyName , AssemblyBuilderAccess.Run, assemblyAttributes);
    ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("ModuleName");
    TypeBuilder typeBuilder = moduleBuilder.DefineType(
          "MyNamespace.TypeName" , TypeAttributes.Public);
    
    typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
    
    // Add a method
    newMethod = typeBuilder.DefineMethod("MethodName" , MethodAttributes.Public);
    
    ILGenerator ilGen = newMethod.GetILGenerator();
    
    // Create IL code for the method
    ilGen.Emit(...);
    
    // ...
    
    // Create the type itself
    Type newType = typeBuilder.CreateType();
    

    This code is just a sample. It could contain errors.

    You can also generate classes by compiling C# source code at runtime using System.CodeDom, but I don't know a lot about that.

提交回复
热议问题