惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
WordPress大学
WordPress大学
C
Check Point Blog
GbyAI
GbyAI
U
Unit 42
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Hugging Face - Blog
Hugging Face - Blog
Vercel News
Vercel News
博客园 - 【当耐特】
美团技术团队
小众软件
小众软件
S
SegmentFault 最新的问题
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog

博客园 - 芭蕉

Model-View-ViewModel(MVVM) with MEF 使用EnvDTE自动格式整个工程 Inversion of Control Duck Typing in C# - 芭蕉 Dynamic Proxy 介绍一个Python进行函数式编程时有用的module - 芭蕉 - 博客园 lambda in F# - 芭蕉 UML类关系图标识速记 Python functions VisualStudio quick tips -- 快速在多个打开的代码文件间切换 VisualStudio quick tips --快速调整字体大小 结合实例实习F#(三)--理解函数式语言中的函数 VisualStudio quick tips --快速打开Properties Page 结合实例学习F#(二) --基本数据类型Discriminated Unions 结合实例学习F#(一) --快速入门 Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance Factory Method 顺时钟方向螺旋状打印矩阵元素 玩转Visual Studio ---Debug篇
C# 4.0 Dynamic --通过DLR直接调用IronPython
芭蕉 · 2009-12-31 · via 博客园 - 芭蕉

前两天在园子里看到一篇用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();
        }       
    }
}

在创建的工程的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):
        self.action()

运行Console app。输出

Decorator...

Hello World