c# - 尝试创建新类型时出现 InvalidProgramException

标签 c# .net reflection types reflection.emit

我有以下代码:

AssemblyBuilder newAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("CustomAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder newModule = newAssembly.DefineDynamicModule("CustomModule");
TypeBuilder newType = newModule.DefineType("CustomType", TypeAttributes.Public);
MethodBuilder newMethod = newType.DefineMethod("GetMessage", MethodAttributes.Public, typeof(string), Type.EmptyTypes);
byte[] methodBody = ((Func<string>)(() => "Hello, world!")).GetMethodInfo().GetMethodBody().GetILAsByteArray();
newMethod.CreateMethodBody(methodBody, methodBody.Length);
Type customType = newType.CreateType();
dynamic myObject = Activator.CreateInstance(customType);
string message = myObject.GetMessage();

但是,当尝试调用 myObject.GetMessage() 时,在最后一行抛出异常:

InvalidProgramException - Common Language Runtime detected an invalid program.

我的代码有什么问题,为什么会抛出这个异常?

最佳答案

问题在于 lambda 表达式包含一个字符串,该字符串在编译时不是以方法体结尾,而是以类型的元数据结尾。 lambda 中的 ldstr 指令通过元数据标记引用字符串。当您获取 IL 字节并将其复制到新方法时,新方法中的 ldstr 将具有无效的元数据标记。

关于c# - 尝试创建新类型时出现 InvalidProgramException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33244880/

相关文章:

c# - 获取驱动器列表,包括共享 RDP 驱动器

c# - 如何浏览主机上的所有 WCF 服务?

.net - 在 .net 中重命名命名空间

c# - 以短格式显示日期(4 月 2 日)

c# - 如何使用 ReflectionPermission 拒绝反射

c# - Linq 中的 Row_number 超过(按 xxx 分区)?

c# - NAudio C#重采样发出麻烦

c# - 在 App.config 中设置 WCF ClientCredentials

c# - 如何解决 C# 反射中泛型方法的歧义

c# - 获取 Enumerable.First() 的 MethodInfo 与 Enumerable.OfType() 的 MethodInfo?