2012-04-28 100 views
2

我有這樣的代碼:錯誤而試圖調用方法

var work = new DynamicMethod("work", null, Type.EmptyTypes); 
      var il = work.GetILGenerator(); 
      il.Emit(OpCodes.Ldstr, "a"); 
      il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)})); 
      var d = (Action)work.CreateDelegate(typeof(Action)); 
      d(); 

我只是想通過System.Reflection.Emit創造新的方法。但它拋出我這個錯誤:

Common Language Runtime detected an invalid program. 

有誰知道我是如何必須將其修復工作或者是錯誤?請幫忙。

回答

4

我認爲你缺少發出回電:

il.Emit(OpCodes.Ldstr, "a"); 
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)})); 
il.Emit(OpCodes.Ret); 
+0

是感謝。我認爲在子方法中不需要添加'ret'。我只有一個問題。在印刷之前的一段時間'操作可能會破壞運行時'。爲什麼? – user35443 2012-04-29 18:01:05

+1

@ user35443我不確定爲什麼你可能會看到「可能會破壞穩定」的信息,但[本文](http://weblogs.asp.net/mehfuzh/archive/2009/06/07/operation-could-destabilize -the-runtime-reflection-emit-and-common-pitfalls.aspx)可能與你描述的問題有關。 – dasblinkenlight 2012-04-29 18:11:52

+0

這不是我一直在尋找的,但我已經解決了這個問題。只是一個小問題:在構造函數'this'對象中是Ldarg_0? – user35443 2012-04-30 04:28:10