2010-06-16 67 views
0

内的所有方法执行此代码后:获得一个脚本文件

var runtime = IronRuby.Ruby.CreateRuntime(); 
    var engine = IronRuby.Ruby.CreateEngine(); 
    var scrope = engine.CreateScope(); 
    engine.ExecuteFile("libtest.rb"); 

我怎样才能获得在C#代码中的一个Ruby类的所有方法?

+1

你的问题是没有意义的,你能澄清?在Ruby中,文件中没有方法。所有方法都在模块或类中。从Ruby,您可以简单地调用例如'Module#instance_methods'来获取模块的所有实例方法,当然,您也可以从C#调用同样的方法。 – 2010-06-16 23:13:33

+0

对不起,我不知道所有的方法必须在课堂或模块中,我编辑了我的问题,谢谢。 – ryudice 2010-06-16 23:28:37

回答

2

我还没有想出一切了没有一类有他们,但这里有一个开始:

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

class IronRubyReflection 
{ 
    static void Main(string[] args) 
    { 
     var engine = Ruby.CreateEngine(); 
     var scope = engine.ExecuteFile("libtest.rb"); 
     dynamic globals = engine.Runtime.Globals; 

     var klass = globals.Klass; 
     var klass_s = klass.GetOrCreateSingletonClass(); 
     var modul = globals.Modul; 
     var modul_s = modul.GetOrCreateSingletonClass(); 

     Console.WriteLine(
      scope.GetVariable<IronRuby.Builtins.RubyMethod>(
       "method_in_the_global_object").Name); 

     Action<string, IronRuby.Builtins.RubyModule, 
      IronRuby.Runtime.Calls.RubyMemberInfo> classprinter = 
       (n, k, i) => { Console.WriteLine(n, k, i); }; 

     klass.ForEachMember(false, 
      IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); 
     klass_s.ForEachMember(false, 
      IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); 
     modul.ForEachMember(false, 
      IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); 
     modul_s.ForEachMember(false, 
      IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); 

     Console.ReadLine(); 
    } 
} 

原谅我的风格,我其实不知道C#。

这是我libtest.rb

def method_in_the_global_object; end 

class Klass 
    def instance_method_in_class; end 
    def self.class_method; end 
end 

class Modul 
    def instance_method_in_module; end 
    def self.module_method; end 
end 

local = Object.new 
def local.singleton_meth; end 

@instance = Object.new 
def @instance.singleton_meth; end 

$global = Object.new 
def $global.singleton_meth; end 

这是输出:

method_in_the_global_object 
instance_method_in_class 
class_method 
Equals 
ReferenceEquals 
allocate 
clr_constructor 
clr_ctor 
clr_new 
new 
superclass 
instance_method_in_module 
module_method 
Equals 
ReferenceEquals 
allocate 
clr_constructor 
clr_ctor 
clr_new 
new 
superclass