这在 我使用DynamicMethod Pluses 的文章C#脚本中有所描述- 第一次调用将比使用CSharpCodeProvider快得多.
这种方法有哪些缺点?
我刚刚读完C# Scripts using DynamicMethod的源代码
我认为最不能容忍的缺点是:太复杂了。在.Net 4.0中,我们可以使用DLR和ironpython来编写脚本,代码行数比使用DynamicMethod少5%。DLR 较新,而且是趋势。
DLR 和 IronPython 的一些代码示例:
var scriptEngine = Python.CreateEngine();
var scriptSource = scriptEngine.CreateScriptSourceFromString(@"# coding=utf-8
def execute(command):
exec(command)
");
scriptScope = scriptEngine.CreateScope();
scriptSource.Execute(scriptScope);
dynamic execute = scriptScope.GetVariable("execute");
execute("print 'hello world'")
Run Code Online (Sandbox Code Playgroud)
仅伪代码,您必须修改上面的代码才能编译和运行。我编写上面的代码是为了向您展示如果使用 DLR 和 Ironpython 而不是 DynamicMethod 将是多么容易。