执行此代码后:
var runtime = IronRuby.Ruby.CreateRuntime();
var engine = IronRuby.Ruby.CreateEngine();
var scrope = engine.CreateScope();
engine.ExecuteFile("libtest.rb");
如何在c#代码中获取ruby类的所有方法?
答案 0 :(得分: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
答案 1 :(得分:1)
或者你可以用C#http://github.com/casualjim/ironrubymvc/blob/master/IronRubyMvc/Core/RubyEngine.cs#L178
来做如果您在类中定义方法而没有它们,则应将它们添加到Object类