六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 120|回复: 0

C#混合IronRuby编程

[复制链接]

升级  70%

7

主题

7

主题

7

主题

童生

Rank: 1

积分
35
 楼主| 发表于 2013-1-19 04:15:41 | 显示全部楼层 |阅读模式
C#编程中,业务部分由IronRuby来实现是一个不错的选择。
 
1.  IDE: SharpDevelop http://www.icsharpcode.net/opensource/sd/
2.  IronRuby: http://ironruby.codeplex.com/releases
下载 IronRuby 1.1.1 Binaries 即可
 
3. 新建C#项目,然后引用 IronRuby Binaries下bin目录的DLL:
IronRuby.dll
IronRuby.Libraries.dll
IronRuby.Libraries.Yaml.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Metadata.dll
 
另外需要引用库 Microsoft.CSharp
 
4. 简单例子
在项目根目录下创建一个service目录放Ruby文件,当然目录你可以自己取名,并且修改相应的地方。
service/apple.rb
class Apple  def say  "Hello MBP!"  endend C#
using System;using Microsoft.Scripting;using Microsoft.Scripting.Hosting;using IronRuby;namespace SharpDLR{class Program{public static void Main(string[] args){var engine = Ruby.CreateEngine();engine.ExecuteFile("service/apple.rb");dynamic ruby = engine.Runtime.Globals;dynamic apple = ruby.Apple.@new();Console.WriteLine("Ruby :"+apple.say());Console.Write("Press any key to continue . . . ");Console.ReadKey(true);}}} 5. 由于编译项目时不会自动复制Ruby文件到bin/Debug目录,所以我们要写一个编译事件。
项目配置:在编译事件(Build Events)的Pre-build event 或者 Post-build event 中加入以下命令
mkdir "$(ProjectDir)$(OutDir)service/"
copy "$(ProjectDir)service/" "$(ProjectDir)$(OutDir)service/"
 
6. 编译运行吧
 
7. 本文只是起到一个入门的作用,可以写一个Ruby初始化文件,载入整个业务所需要的Ruby类。例:
bootstrap.rb
load 'service/product.rb'load 'service/customer.rb'load 'service/orderitem.rb'load 'service/order.rb' 
相应的C#调用为
 
var engine = Ruby.CreateEngine();engine.ExecuteFile("service/bootstrap.rb");dynamic ruby = engine.Runtime.Globals;dynamic customer = ruby.Customer.@new("Davy Brion", "davy@gmail.com");dynamic product1 = ruby.Product.@new("product1", 50);dynamic product2 = ruby.Product.@new("product2", 60);dynamic order = ruby.Order.@new(customer, null, DateTime.Now); order.add_item(ruby.OrderItem.@new(product1, 5));order.add_item(ruby.OrderItem.@new(product2, 5));... 开始享受混合编程的乐趣吧!
 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表