有没有简单的方法来创建方法并在C#中动态设置它的主体?
我在字符串中持有方法体。 我想动态创建方法。 但我不知道,如何设置它的身体。 我看到使用CodeDom非常乏味。 我看到使用Emit和OpCodes。 有没有办法从字符串变量中使用现成的代码?
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
您需要查看这些名称空间:
System.Reflection; System.CodeDom.Compiler; Microsoft.CSharp;
这可以帮助您入门: http : //www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
听起来你想要的是“编译器即服务”。 这不是在MS .NET 4.0中,但可能在以后的版本中。 但它已经在Mono中了。 在此之前,可用的选项包括:
- 使用
CSharpCodeProvider
,但你必须通过reflection将其作为方法加载(并创建一个委托) - 使用
CodeDom
- 使用
Reflection.Emit
- 使用
Expression
在4.0中, Expression
API远比3.5中更丰富,允许大多数常见的构造没有CodeDom
的痛苦。 但是不要打折Reflection.Emit
– 需要一点时间来了解ILGenerator
并使用堆栈,但它并没有人们想象的那么糟糕。
作为旁注,请不要使用DynamicMethod
Invoke
,除非您只想执行一次。 更好的方法是使用CreateDelegate
,然后存储( CreateDelegate
用)该委托:
var dm = new System.Reflection.Emit.DynamicMethod("My_method", typeof(string), null); var il = dm.GetILGenerator(); il.Emit(OpCodes.Ldstr, "Hello, world!"); il.Emit(OpCodes.Ret); Func func = (Func )dm.CreateDelegate(typeof(Func )); var s = func();
或者使用Expression
API:
var lambda =Expression.Lambda>(Expression.Constant("Hello, world")); var func = lambda.Compile(); var s = func();
将其保存到.CS文件并动态编译和执行。