C# 4.0 动态调用 IronPython

想一下这样的应用场景 现在我们使用NHibernate是使用xml来配置数据库链接 数据库方言 等等等等

但是通过调用IronPython来执行 *.py 我们只需要在 py文件中写一个方法 然后在这个方法中直接写代码配置就可以了

而这个方法接受的参数是一个new Configuration()的实例 这样我们就可以做到在这个py中用python的代码来进行配置

是不是很棒呢?当然理论上是可行的 具体行不行呢?我们来做一个小例子

新建一个解决方案 InvokeIronPython

在这个解决方案下建两个项目

类库项目:Services

Console项目: ConsoleApp

在Services项目下建一个EchoServices.cs 代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Services {
     public class EchoServices {
         public string Echo(string message) {
             return message;        
}    
}
}

在ConsoleApp项目添加对IronPython的一些dll的引用(当然你要装了IronPython才会有这些dll。。。)

这些文件你可以在IronPython的安装目录下找到

IronPython.dll, IronPython.Modules.dll, Microsoft.Scripting.dll, Microsoft.Dynamic.dll

好了 现在我们在ConsoleApp目录下写一个文件

test.py 内容如下:

当然这个文件的属性是要设置copy if newer(你懂的-_-)

代码如下

import clr #我们要调用C#的类库 
clr.AddReference("Services") #添加对类库的引用
from Services import EchoServices #你懂的。。。
def zerg():
 es = EchoServices()
 return es.Echo("这是一个来自Services程序集的EchoServices类实例的Echo方法的执行返回结果!")

接下来是program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using
 System.Text;
using
 IronPython.Hosting;
using
 Microsoft.Scripting.Hosting;
using
 Services;
namespace ConsoleApp
{    
class
 Program    
{
         static void Main(string[] args)
         {
             EchoServices es = new EchoServices();
             var ipy = Python.CreateRuntime();
             dynamic test = ipy.UseFile("test.py");
             Console.WriteLine(test.zerg());
         }
     }
 }

大功告成 你可以运行一下看看

这是在C# 4.0中动态调用IronPython脚本的一种方式,至于有没有用就要看你的应用场景了,呵呵。

posted on 2011-05-20 23:10  ThinkInSharp  阅读(802)  评论(0编辑  收藏  举报

导航