简体   繁体   English

如何将C#类型转换为IronRuby类型,反之亦然?

[英]How to convert C# types to IronRuby types and vice versa?

For example: 例如:

ruby code (just for test): 红宝石代码(仅用于测试):

def process_initial_array (ar)
     ar.join(" ")
end

c# code: Here I create List of strings and pass it to the IronRuby c#代码:在这里,我创建字符串列表并将其传递给IronRuby

List<string> source_values = new List<string>();

it fills; 它充满了;

label2.Text=IronRuby.CSharp.BasicInteraction.calculator(source_values);


namespace IronRuby.CSharp
{
    public class BasicInteraction
    {internal static string calculator(List<string> source_values)
        {
            var rubyEngine = Ruby.CreateEngine();
            var scope = rubyEngine.ExecuteFile("math_logic.rb");
            string result = rubyEngine.Operations.InvokeMember(scope, "process_initial_array", source_values);
            return result;
        }
    }
}

It evokes: 它引起:

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Anonymously Hosted DynamicMethods Assembly

Additional information: Unable to convert implicitly "IronRuby.Builtins.MutableString" to "string". There is explicit conversion.

OK, I found IronRuby string method to_clr_string in related questions, so the question is where I can find documentation about same methods for other types? 好的,我在相关问题中找到了IronRuby字符串方法to_clr_string,所以问题是在哪里可以找到关于其他类型的相同方法的文档?

After a brief look on the IronRuby source code I could only find to_clr_string and to_clr_type (to convert to System.Type ) that seem to be relevant to your question. 简要浏览IronRuby 源代码后,我只能找到似乎与您的问题有关的to_clr_stringto_clr_type (转换为System.Type )。 Thus, I assume those are the only conversion methods you need to convert between built-in ruby types and CLR types. 因此,我假设这些是您需要在内置的ruby类型和CLR类型之间进行转换的唯一转换方法。 Other types should be the same types as their CLR counterparts. 其他类型与CLR对应类型相同。

Note that there're also other methods to convert from ruby strings to other primitive types like int ( to_i ) and double ( to_f ). 请注意,还有其他方法可以将红宝石字符串转换为其他原始类型,例如intto_i )和doubleto_f )。

In your example, you could explicitly convert the result to string : 在您的示例中,您可以将结果显式转换为string

var result = (string)rubyEngine.Operations.InvokeMember(
  scope, "process_initial_array", source_values);

This way, you don't have to call to_clr_string on the Ruby side. 这样,您不必在Ruby端调用to_clr_string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM