












前两天在园子里看到一篇用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();在创建的工程的bin\debug目录下,添加script.py.代码如下,一个很简单的wrapper,仅供验证之用。
def wrapper(function):
def inner(self):
print "Decorator... "
return function(self)
return innerclass decorator(object):
def __init__(self, function):
self.action = function
@wrapper
def execute(self):运行Console app。输出
Decorator...
Hello World
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。