我想将 Child
作为动态类型添加到动态程序集中:
public abstract class Parent { } // I want to define this statically
public class Child : Parent { // I want to define this dynamically
private Child() : base() { }
}
我关注了this示例。
我添加了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
。作为documentation说:
Before a type is used, the
TypeBuilder.CreateType
method must be called.CreateType
completes the creation of the type.
您可能不需要使用它返回的 Type
对象来执行任何操作,但您仍然需要这样做。毕竟加载类型算作“使用类型”。
你应该这样做:
typeBuilder.CreateType();
在DefineDefaultConstructor
之后。
关于c# - 无法在 .NET Core 中创建动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69602204/