---
title: "C#混合IronRuby编程"
author: "myrev"
date: "2011-01-26T20:36:16Z"
tags: []
categories: ["编程语言"]
slug: "c-ironruby"
draft: false
lastmod: "2011-01-26T20:38:18Z"
id: 897657
url: "https://myrev.iteye.com/blog/897657"
---

C#编程中，业务部分由IronRuby来实现是一个不错的选择。

 

1.  IDE: SharpDevelop [http://www.icsharpcode.net/opensource/sd/](http://www.icsharpcode.net/opensource/sd/)

2.  IronRuby: [http://ironruby.codeplex.com/releases](http://ironruby.codeplex.com/releases)

下载 [IronRuby 1.1.1 Binaries](http://ironruby.codeplex.com/releases/view/49097#DownloadId=159562) 即可

 

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!"
  end

end
```

 

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));

...

```

 

开始享受混合编程的乐趣吧！