【问题标题】:Retrieving accessors in IronRuby在 IronRuby 中检索访问器
【发布时间】:2010-04-14 20:28:17
【问题描述】:

我试图弄清楚如何检索存储在 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");

【问题讨论】:

    标签: ironruby


    【解决方案1】:

    [编辑:刚刚安装了 VS 和 IronRuby 并测试了所有内容。]

    我能想到的最简单的方法是将marcy 输入为dynamic 而不是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 并提供了模拟 Ruby 的 method_missingTryGetProperty 的实现,所以总而言之,您可以这样做:

    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 全局常量,而不必将其作为字符串传入,您只需在 Person 类上调用 new 方法(尽管很遗憾,您必须将其转义,因为 new 是一个保留字,尽管解析器知道其中的区别是微不足道的)来创建一个实例。

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多