使用DynamicMethod进行脚本编写

本文关键字:脚本 DynamicMethod 使用 | 更新日期: 2023-09-27 17:58:07

这在文章C#脚本中使用DynamicMethod进行了描述Pluses我看到了-第一个调用将比使用CSharpCodeProvider快得多。

这种方法的缺点是什么?

使用DynamicMethod进行脚本编写

我刚刚用DynamicMethod 读完了C#脚本的源代码

我认为最不能容忍的缺点是:太复杂了。在.Net 4.0中,我们可以使用DLR和ironpython来执行脚本,其中5%的代码行使用DynamicMethod。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'")

只有伪代码,您必须修改上面的代码才能编译和运行。我编写上面的代码是为了向您展示如果您使用DLR和Ironpython而不是DynamicMethod会有多容易。

DynamicMethod需要直接写入IL。这篇文章的作者显然已经编写了自己的编译器,将C#脚本翻译成可以加载到DynamicMethod中的IL,但这可能非常脆弱。CSharpCodeProvider使用csc,这是在Visual Studio中运行的编译器(几乎),因此它可能更可靠。