簡體   English   中英

嘗試創建新類型時出現InvalidProgramException

[英]InvalidProgramException when trying to create a new type

我有以下代碼:

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 - 公共語言運行時檢測到無效程序。

我的代碼有什么問題,為什么拋出這個異常?

問題是lambda表達式包含一個字符串,當編譯時,字符串不是以方法體結尾,而是在類型的元數據中。 lambda中的ldstr指令通過元數據標記引用字符串。 當您獲得IL字節並復制到新方法時,新方法中的ldstr將具有無效的元數據標記。

如果我不得不冒險猜測,我會說這是因為這句話:

byte[] methodBody = ((Func<string>)(() => "Hello, world!")).GetMethodInfo().GetMethodBody().GetILAsByteArray();

我不確定究竟什么簽名(Func<string>)( () => "Hello, world!" )會有,但它可能不是正確的(一個接受你定義類型的隱式參數) 。

我建議使用方法構建器的GetILGenerator方法來執行此操作:

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);

var il = newMethod.GetILGenerator();
// return "Hello, world!";
il.Emit( OpCodes.Ldstr, "Hello, world!" );
il.Emit( OpCodes.Ret );

Type customType = newType.CreateType();
dynamic myObject = Activator.CreateInstance(customType);
string message = myObject.GetMessage();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM