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