【问题标题】:Getting all methods inside a script file获取脚本文件中的所有方法
【发布时间】:2010-06-16 22:41:55
【问题描述】:

执行此代码后:

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

如何在 c# 代码中获取 ruby​​ 类的所有方法?

【问题讨论】:

  • 你的问题没有意义,你能澄清一下吗?在 Ruby 中,文件中没有方法。所有方法都在模块或类中。在 Ruby 中,您可以简单地调用例如 Module#instance_methods 来获取模块的所有实例方法,当然您也可以从 C# 中调用相同的方法。
  • 对不起,我不知道所有方法都必须在类或模块中,我编辑了我的问题,谢谢。

标签: c# ruby ironruby


【解决方案1】:

我还没有弄清楚一切,但这是一个开始:

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
类方法
等于
引用等式
分配
clr_constructor
clr_ctor
clr_new
新的
超类
instance_method_in_module
模块方法
等于
引用等式
分配
clr_constructor
clr_ctor
clr_new
新的
超类

【讨论】:

    【解决方案2】:

    或者您可以从 C# http://github.com/casualjim/ironrubymvc/blob/master/IronRubyMvc/Core/RubyEngine.cs#L178 进行操作

    如果你定义的方法没有在一个类中,它们应该被添加到 Object 类中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 2011-11-18
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      相关资源
      最近更新 更多