嵌入 IronRuby 到 CLR 主程序的例子

下面的代码实现了 IronRuby 脚本继承 C# 主程序提供的类,并被 C# 调用的例子,对于使用 Iron 语言来做 .NET 程序插件或脚本是一个很好的参考。

using System;
using System.Reflection;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronRuby;

namespace IronRubyTest1
{
    public class Human
    {
        protected string GetInternalCondition()
        {
            return "all good";
        }
    }

    class Program
    {
        static void Main( string [] args)
        {
            const string RubyCode = @"
class Doctor < IronRubyTest1::Human
  def check_condition()
    puts 'Condition: ' + get_internal_condition()
  end
end";
            ScriptRuntime runtime = Ruby . CreateRuntime();
            ScriptEngine engine = Ruby . GetEngine( runtime);
            ScriptScope scope = engine . CreateScope();

            //让 DLR 载入包含 Human 类的 Assembly
            runtime . LoadAssembly( Assembly . GetExecutingAssembly());
            engine . Execute( RubyCode , scope); //执行 Ruby 代码
            dynamic globals = engine . Runtime . Globals;
            dynamic house = globals . Doctor . @new(); //创建 Doctor 的实例
            house . check_condition();

            Console . WriteLine( "Press any key to close...");
            Console . ReadKey();
        }
    }
}

代码下载:http://pastebin.com/0tHWuAmH

参考资料

http://www.voidspace.org.uk/ironpython/hosting_api.shtml#id2

《IronRuby In Action》

转载于:https://www.cnblogs.com/oldrev/archive/2011/05/29/2062154.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值