【问题标题】:Pass an array from IronRuby to C#将数组从 IronRuby 传递到 C#
【发布时间】:2010-03-19 23:25:27
【问题描述】:

我确定这是一个简单的解决方法,但我找不到它,但这里是:

我在程序集(比如说 SOTest.dll)中有一个 C# 类(我们称之为 Test)。 以下是我正在做的事情:

private List<string> items;

public List<string> list_items()
{
    return this.items;
}

public void set_items(List<string> new_items)
{
    this.items = new_items;
}

在我运行的 IronRuby 解释器中:

>>> require "SOTest.dll"
true
>>> include TestNamespace
Object
>>> myClass = Test.new
TestNamespace.Test
>>> myClass.list_items()
['Apples', 'Oranges', 'Pears']
>>> myClass.set_items ['Peaches', 'Plums']
TypeError: can't convert Array into System::Collections::Generic::List(string)

无论我将参数设为 'List'、'List' 还是 'string[ ]',我都会收到类似的错误。

什么是正确的语法?我在任何地方都找不到记录在案的类型映射(因为考虑到 Ruby 可以做什么,在某些情况下定义它可能太复杂了)。

编辑:

看起来我试图做的事情是不可能的。我必须在 .NET 项目中包含 IronRuby 程序集,以便输入可以是 IronRuby 类型,以保持脚本界面更简洁。

如果有人想出一种方法让它按我最初想要的方式工作,我会更改接受的答案。

【问题讨论】:

    标签: c# ironruby


    【解决方案1】:

    您将不得不稍微不同地构建列表:

    ls = System::Collections::Generic::List.of(String).new
    ls.add("Peaches")
    ls.add "Pulms"
    

    【讨论】:

    • 这是真的吗? List&lt;string&gt; 有一个构造函数,它接受 IEnumerable&lt;string&gt;,这肯定是 IronRuby 数组必须支持的。
    • 我如何创建一个字符串数组?
    【解决方案2】:

    从未使用过,但我猜是这样的:

    myClass.set_items(System::Collections::Generic::List(string).new ['Peaches', 'Plums'])
    

    即从数组中构造一个List&lt;string&gt;。我对System::Collections::Generic::List(string) 部分持怀疑态度,但从错误消息来看,这就是在 IronRuby 中给出List&lt;string&gt; 的完全限定名称的方法。

    【讨论】:

    • 令人惊讶的是,这不起作用(TypeError: can't convert Array into Fixnum)。我认为 RubyArray 继承自 IEnumerable,所以我认为它会起作用。
    • 听起来像是在尝试调用 List 构造函数的错误重载。也许这在 IronRuby 中还不能正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多