0

我试图弄清楚如何检索存储在 Person 类中的值。问题只是在我定义了 Person 类的实例之后,我不知道如何在 IronRuby 代码中检索它,因为实例名称在 .NET 部分中。

 /*class Person
        attr_accessor :name

                def initialize(strname)
                    self.name=strname
                end
    end*/

    //We start the DLR, in this case starting the Ruby version


 ScriptEngine engine = IronRuby.Ruby.CreateEngine();
        ScriptScope scope = engine.ExecuteFile("c:\\Users\\ron\\RubymineProjects\\untitled\\person.rb");

    //We get the class type
    object person = engine.Runtime.Globals.GetVariable("Person");

    //We create an instance
    object marcy = engine.Operations.CreateInstance(person, "marcy");
4

1 回答 1

2

[编辑:刚刚安装了 VS 和 IronRuby 并测试了一切。]

我能想到的最简单的方法是键入marcyasdynamic而不是object,然后调用访问器(如果我没记错的话,它实际上表示为 .NET 端的属性):

dynamic marcy = engine.Operations.CreateInstance(person, "marcy");
var name = marcy.name;

如果您不使用 .NET 4,则必须通过“丑陋”的基于字符串的 API:

var name = engine.Operations.InvokeMember(marcy, "name");

顺便说一句:如果您使用.NET 4,您还可以简化一些其他代码。例如,Globals实现IDynamicObject并提供TryGetProperty模拟 Ruby 的实现method_missing,所以总而言之,您可以执行以下操作:

var engine = IronRuby.Ruby.CreateEngine();
engine.ExecuteFile("person.rb");
dynamic globals = engine.Runtime.Globals;
dynamic person = globals.Person;
dynamic marcy = person.@new("marcy"); // why does new have to be a reserved word?
var name = marcy.name;

请注意,您如何只需“点入”Globals即可获取Person全局常量,而不必将其作为字符串传递,您只需调用类new上的方法Person(尽管不幸的是,您必须将其转义,因为它new是保留字,尽管解析器知道差异是微不足道的)创建一个实例。

于 2010-04-14T21:34:07.823 回答