我在字符串中保存方法體。我想動態地創建方法。但我不知道,如何設置它的身體。我看到使用CodeDom非常乏味的方式。我看到使用OpCodes發射。有沒有辦法使用字符串變量的現成代碼?是否有任何簡單的方法來創建方法並在C#中動態設置它的主體?
string method_body = "return \"Hello, world!\";"; //there is method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
typeof(string), new Type[] { }); //any way to create method dynamically
//any way to set body
string result = (string)dm.Invoke(...); //I need write result in variable
哦,謝謝!文中提供了動態編譯的準備課程,您可以參考它。 只需寫 ww腳本lo_script = new wwScripting(「CSharp」); lo_script.lSaveSourceCode = true; lo_script.AddAssembly(「mscorlib.dll」); string result =(string)lo_script.ExecuteCode(method_body,new object [] {.../* params */...}); 這是非常方便的方式。 – greatromul 2010-06-13 14:31:08
這種方式可行,但只有在絕對信任輸入代碼的情況下,才應使用該方法。如果一些最終用戶(或者可能是一些可下載的內容)有能力運行代碼,那麼您應該非常小心。只是一個供參考,所以它不會讓你陷入困境。 – drharris 2010-06-15 03:07:13