65.9K
CodeProject 正在变化。 阅读更多。
Home

从 C#4.0 调用 IronRuby 方法的分步指南

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.76/5 (16投票s)

2010年10月25日

CPOL

1分钟阅读

viewsIcon

34262

downloadIcon

257

一个简短的演示,展示如何调用用 IronRuby 1.1 编写的方法,并从 C# 环境动态调用该方法。

引言

IronRuby 是 Ruby 编程语言的一个开源实现,用于 .NET,它大量依赖于微软的动态语言运行时(引用自 IronRuby 网站

本文将逐步演示如何使用 dynamic 关键字从 C#4.0 调用 IronRuby 1.1 函数。

使用代码

步骤 1:Code Plex 下载最新版本的 Iron Ruby。

步骤 2: 安装软件。

步骤 3: 对于此演示,我们使用 add.rb Ruby 文件,该文件只有一个 Add 方法,执行将两个数字作为参数传递给该方法的加法运算。

步骤 4: 我们使用控制台应用程序进行演示。我们需要做的第一件事是添加如下所示的 dll 文件

1.jpg

步骤 5: 函数调用只需三个步骤即可完成,如下所示

class Program
    {
        static void Main(string[] args)
        {
            //Step 1: 
            //Creating a new script runtime   
            var ironRubyRuntime = Ruby.CreateRuntime();

            try
            {
                //Step 2:
                //Load the Ruby file/script into the memory
                //Should be resolve at runtime
                dynamic loadIRuby = ironRubyRuntime.UseFile(@"add.rb");

                //Step 3:
                //Invoke the method and print the result
                Console.WriteLine(
               string.Format("Addition result from Iron Ruby method for {0} and  
               {1} is {2}",100, 200, loadIRuby.add(100, 200)));               
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey(true);
        }
    }

第一行

var ironRubyRuntime = Ruby.CreateRuntime();
加载 Iron Ruby 库以及执行 python 脚本所需的 DLR 代码。第二行
dynamic loadIRuby = ironRubyRuntime.UseFile(@"add.rb");
将 Ruby 脚本加载到内存中。dynamic 变量 (loadIRuby) 的重要性在于 Ruby 调用是在运行时解析的。最后一行,即
Console.WriteLine(
     string.Format("Addition result from Iron Ruby method for 
    {0} and {1} is {2}", 100, 200, 
    loadIRuby.add(100, 200)));
只是为了调用 Ruby 方法并显示结果。步骤 6: 这是输出 3.jpg

参考文献

IronRuby 入门

结论

在本简短教程中,我们了解了如何从 C# 4.0 调用 IronRuby 方法。

非常感谢您对该主题的评论,以便改进该主题。

感谢阅读本文。

© . All rights reserved.