从IronRuby返回CLR类型

时间:2009-02-25 07:28:18

标签: c# ironruby

我正在尝试从Iron Ruby返回一个CLR对象。

我在C#

中定义了以下CLR类型
public class BuildMetaData
{
    public string Description { get; set; }
}

我有以下IronRuby文件:

$:.unshift(File.dirname(__FILE__) + '/../bin/Debug') 
require 'mscorlib'
require 'Horn.Core.DSL.Domain'

class MetaDataFactory
    def return_meta_data()
        meta = Horn::Core::DSL::Domain::BuildMetaData.new
        meta.Description = "A description of sorts"
        meta
    end
end

我有以下测试失败:

[Fact]
public void Then_a_build_metadata_object_is_returned()
{                       
    var engine = Ruby.CreateEngine();

    engine.ExecuteFile("test.rb");

    var code = String.Format("{0}.new.method :{1}", "MetaDataFactory", "return_meta_data");

    var action = engine.CreateScriptSourceFromString(code).Execute();

    var result = (BuildMetaData)engine.Operations.Call(action);

    Assert.Equal(result.Description, "A description of sorts");
}

尝试转换从IronRuby返回的对象时失败。

我收到以下错误消息:

[A] Horn.Core.DSL.Domain.BuildMetaData无法转换为[B] Horn.Core.DSL.Domain.BuildMetaData。类型A源自'Horn.Core.DSL.Domain,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'在上下文'LoadNeither'位置'C:\ Projects \ horn \ branches \ ruby​​dsl \ src \ Horn .Dsl.Specificatioin \ BIN \调试\ Horn.Core.DSL.Domain.dll”。类型B源自'Horn.Core.DSL.Domain,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'在上下文'Default'位置'C:\ Users \ paul.cowan \ AppData \ Local \ Temp \ 1vt2usw2.rxf \ Horn.Dsl.Specificatioin \组件\ DL3 \ 1d5ed945 \ 7c19e429_1a97c901 \ Horn.Core.DSL.Domain.DLL”。

是否可以从Iron Ruby返回CLR类型

2 个答案:

答案 0 :(得分:4)

不是使用特制的Ruby字符串获取方法,然后使用C#调用该方法,而是从C#调用Ruby代码的首选方法如下:

var engine = IronRuby.Ruby.CreateEngine()
engine.ExecuteFile("test.rb")
var klass = engine.Runtime.Globals.GetVariable("MetaDataFactory")
var instance = engine.Operations.CreateInstance(klass)
engine.Operations.InvokeMember(instance, "return_meta_data")

〜麦

答案 1 :(得分:1)

实际上这完全取决于影子复制。

我的代码最终看起来像这样:

[Fact]
public void Then_the_object_should_be_accessible_in_csharp()
{                       
    var engine = Ruby.CreateEngine();

    engine.Runtime.LoadAssembly(typeof (BuildMetaData).Assembly);

    engine.ExecuteFile(buildFile);

    var klass = engine.Runtime.Globals.GetVariable("MetaDataFactory");

    var instance = (RubyObject)engine.Operations.CreateInstance(klass);

    //You must have shadow-copying turned off for the next line to run and for the test to pass.
    //E.g. in R# "ReSharper/Options/Unit Testing/Shadow-Copy Assemblies being tested" should be un-checked.
    var metaData = (BuildMetaData)engine.Operations.InvokeMember(instance, "return_meta_data");

    Assert.Equal(metaData.Description, "A description of sorts");

    Assert.Equal(metaData.Dependencies.Count, 1);
}

但如果我从R#测试运行器关闭了阴影复制,那么现在测试通过了。