2010-06-16 66 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