我将方法体保存在字符串中。我想动态创建方法。但我不知道,如何设置它的身体。我看到使用 CodeDom 的方式非常乏味。我看到使用 Emit 和操作码。有什么方法可以使用字符串变量中的现成代码吗?
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
听起来你想要的是“编译器即服务”。这不在 MS .NET 4.0 中,但可能在更高版本中。不过它已经在 Mono 中了。在那之前,可用的选项有:
- use
CSharpCodeProvider
,但是您必须通过反射将其作为方法加载(并为其创建委托)
- use
CodeDom
- use
Reflection.Emit
- use
Expression
在 4.0 中,Expression
API 比 3.5 中丰富得多,允许最常见的构造,而无需担心CodeDom
。但不要打折Reflection.Emit
- 需要一点时间才能恢复头脑ILGenerator
并使用堆栈,但它并不像人们想象的那么糟糕。
作为旁注,不要使用Invoke
from DynamicMethod
除非你只想执行一次。更好的方法是使用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<string> func = (Func<string>)dm.CreateDelegate(typeof(Func<string>));
var s = func();
或者与Expression
API:
var lambda =Expression.Lambda<Func<string>>(Expression.Constant("Hello, world"));
var func = lambda.Compile();
var s = func();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)