无法在 .NET Core 中创建动态类型

Cannot create dynamic type in .NET Core

我想将 Child 作为动态类型添加到动态程序集:

public abstract class Parent { }       // I want to define this statically

public class Child : Parent {          // I want to define this dynamically
  private Child() : base() { }
}

我遵循了 示例。

我添加了 nuget 包 System.Reflection.Emit (v 4.7.0)。

然后写了这个:

using System;
using System.Reflection;
using System.Reflection.Emit;

public abstract class Base { }

public class Program {

  public static void Main() {

    // define dynamic assembly
    var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
    var moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

    // define dynamic type
    var typeName = "Child";
    var typeBuilder = moduleBuilder.DefineType(
      typeName,
      TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
      typeof(Base));
    typeBuilder.DefineDefaultConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
    //typeBuilder.CreateType();   // this was missing - see accepted answer below

    // test it
    try {
      typeBuilder.Assembly.GetTypes();                 // <--- throws
    }
    catch (ReflectionTypeLoadException exception) {
      Console.WriteLine(exception.Message);
    }
  }

}

它抛出这个:

Unable to load one or more of the requested types. Could not load type 'Child' from assembly '28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

我在单元测试项目中失败了。它也在 dotnetfiddle.

上失败了

我做错了什么?

你忘了打电话给 CreateType. As the documentation 说:

Before a type is used, the TypeBuilder.CreateType method must be called. CreateType completes the creation of the type.

您可能不需要使用它 returns 的 Type 对象来做任何事情,但您仍然需要这样做。加载类型毕竟是“使用类型”。

你应该做的:

typeBuilder.CreateType();

在你之后 DefineDefaultConstructor.