【发布时间】:2021-10-17 07:30:20
【问题描述】:
我想将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);
}
}
}
它抛出这个:
无法加载一种或多种请求的类型。 无法从程序集“28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null”加载类型“Child”。
这对我来说在单元测试项目中失败了。在dotnetfiddle 上也失败了。
我做错了什么?
【问题讨论】:
标签: c# .net-core reflection .net-5 reflection.emit