2010-04-14 51 views
0

我想弄清楚如何检索存储在Person类中的值。问题在于,在定义Person类的实例后,我不知道如何在IronRuby代码中检索它,因为实例名称位于.NET部分。在IronRuby中检索访问器

/*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"); 

回答

2

[编辑:刚装VS和IronRuby和测试,一切]

我能想到的最简单的方法是键入marcydynamic代替object,并调用访问(这要是我没记错的话实际上是表示在.NET方面的属性):

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

如果你不使用.NET 4,你必须要经过“难看”基于字符串的API:

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

BTW:如果您使用.NET 4中,您还可以简化你的一些其他的代码。例如,Globals实现IDynamicObject,并提供模拟Ruby的method_missing,所以这一切的一切,你可以做这样的事情的TryGetProperty系统的实现:

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

注意如何你可以“点到” Globals得到Person全球常量,而不必将其作为字符串传入,您可以调用Person类中的new方法(尽管因为new是保留字,您不幸必须转义它,尽管分析器知道差异)来创建一个实例。