无法在.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(v4.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);
}
}
}

它抛出了这个:

无法加载一个或多个请求的类型。无法从程序集"28266a72-fc60-44ac-8e3c-3ba7461c6be4,版本=0.0.0.0,区域性=中性,PublicKeyToken=null"加载类型"Child"。

这对我来说在一个单元测试项目中失败了。它在互联网上也失败了。

我做错了什么?

您忘记调用CreateType。正如文件所说:

在使用类型之前,必须调用TypeBuilder.CreateType方法。CreateType完成类型的创建。

您可能不需要使用它为任何事情返回的Type对象,但您仍然需要这样做。加载该类型计数为"0";使用类型";毕竟

你应该做:

typeBuilder.CreateType();

在你DefineDefaultConstructor之后。