我有以下代码:
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/