瑞雪年

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: 订阅 订阅 :: 管理 ::

Mono.CSharp.Evaluator提供了方便的动态编译功能,但默认的Compile方法,
只支持无参的方法,如:

Mono.CSharp.Evaluator evaluator = new Mono.CSharp.Evaluator(new Mono.CSharp.CompilerSettings(), new Mono.CSharp.Report(new ConsoleReportPrinter()));
var method = evaluator.Compile("System.Console.WriteLine(\"dynamic compiled\");");
// or with return value.
method = evaluator.Compile("new System.DateTime();");
object value = null;
method(ref value);


其实,要支持带参数的方法也很容易,使用Lambda表达式轻松实现:

evaluator.ReferenceAssembly(typeof(Form1).Assembly);
var action = (System.Action<WindowsFormsApplication1.Form1, object>)evaluator.Evaluate("new System.Action<WindowsFormsApplication1.Form1, object>((instance, value) => { instance.Test(value); });");
action(this, "test8");


于是,本人写了个EvaluatorExtension将这样的代码简化一下:

var action = evaluator.Compile<Action<Form1, object>>("(instance, value) => { instance.Test(value); }");
action(this, "test12");
// or with return value
var func = evaluator.Compile<Func<Form1, object, string>>("(instance, value) => { instance.Test(value); return (string)value; }");
string value = func(this, "test13");


或者,使用参数的方法定义“参数名”:

var action = evaluator.Compile<Action<Form1, object>>(new[] { "instance", "value" }, "instance.Test(value);");

Mono.CSharp.dll 下载: Mono.CSharp.dll




posted on 2011-11-27 12:48  瑞雪年  阅读(749)  评论(0编辑  收藏  举报