C# 4.0 Dynamic --通过DLR直接调用IronPython
前两天在园子里看到一篇用C#实现Python Decorator的文章,看的时候就在想应该可以用C# 4.0 Dynamic来搞。今中午有时间试了一下,果然可以.
本文假设你己安装了VS2010 Beta2和 IronPython 2.6 for .NET 4.0 Beta2, 首先创建一个Console App并引用如下Dll (可以在你的IronPython安装目录中找到)
IronPython.dll
IronPython.Modules.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.dll
然后用下面的代码替换掉默认生成的代码
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
namespace Decorator.Try
{
class Program
{
static void Main(string[] args)
{
Action action = () => Console.WriteLine("Hello World");
ScriptRuntime runtime = Python.CreateRuntime();
dynamic script = runtime.UseFile("script.py");
dynamic decorator = script.decorator(action);
decorator.execute();
}
}
}
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
namespace Decorator.Try
{
class Program
{
static void Main(string[] args)
{
Action action = () => Console.WriteLine("Hello World");
ScriptRuntime runtime = Python.CreateRuntime();
dynamic script = runtime.UseFile("script.py");
dynamic decorator = script.decorator(action);
decorator.execute();
}
}
}
在创建的工程的bin\debug目录下,添加script.py.代码如下,一个很简单的wrapper,仅供验证之用。
def wrapper(function):
def inner(self):
print "Decorator... "
return function(self)
return inner
class decorator(object):
def __init__(self, function):
self.action = function
@wrapper
def execute(self):
self.action()
def inner(self):
print "Decorator... "
return function(self)
return inner
class decorator(object):
def __init__(self, function):
self.action = function
@wrapper
def execute(self):
self.action()
运行Console app。输出
Decorator...
Hello World