在IronRuby中包含接口的问题

本文关键字:问题 接口 包含 IronRuby | 更新日期: 2023-09-27 18:19:15

我有一个界面,看起来像:

interface IMyInterface {
    MyObject DoStuff(MyObject o);
}

我想在IronRuby中编写这个接口的实现,并返回这个对象供以后使用。

但是当我尝试做像

这样的事情时
var code = @"
    class MyInterfaceImpl
        include IMyInterface
        def DoStuff(o)
            # Do some stuff with o
            return o
        end
    end
    MyInterfaceImpl.new";
Ruby.CreateEngine().Execute<IMyInterface>(code);

我得到一个错误,因为它不能被强制转换为IMyInterface。是我做错了吗,还是我不可能做我想做的事?

在IronRuby中包含接口的问题

你想做的是可能的;IronRuby支持通过将接口混合到类中来实现接口。

运行你的例子,我得到这个异常:

Unhandled Exception: System.MemberAccessException: uninitialized constant MyInte
rfaceImpl::IMyInterface

这并不意味着对象不能被强制转换为IMyInterface,它只是意味着Ruby引擎不知道IMyInterface是什么。这是因为你必须告诉IronRuby在哪些程序集中查找IMyInterface,使用ScriptRuntime.LoadAssembly。例如,要加载当前程序集,可以这样做:

ruby.Runtime.LoadAssembly(typeof(IMyInterface).Assembly);

下面的示例展示了如何通过调用接口上的方法从c#调用ruby定义的方法:

public class MyObject {
}
public interface IMyInterface {
    MyObject DoStuff(MyObject o);
}
public static class Program {
  public static void Main(string[] args) {
    var code = @"
    class MyInterfaceImpl
        include IMyInterface
        def DoStuff(o)
            # Do some stuff with o
            puts o
            return o
        end
    end
    MyInterfaceImpl.new";
    var ruby = IronRuby.Ruby.CreateEngine();
    ruby.Runtime.LoadAssembly(typeof(MyObject).Assembly);
    var obj = ruby.Execute<IMyInterface>(code);
    obj.DoStuff(new MyObject());
  }
}

在IronRuby中实现CLR接口并将其传回CLR是不可能的。在你的例子中,'MyInterfaceImpl'是一个Ruby类,而不是'IMyInterface'的CLR实现。

我更正一下,根据Jimmy Schementi的帖子。

你可以在。net代码中使用IronRuby类型作为动态对象: <>之前var engine = Ruby.CreateRuntime().GetEngine("rb");引擎。Execute("/*你的脚本到这里*/");dynamic rubyScope = engine.Runtime.Globals;动态myImplInstance = rubyScope.MyInterfaceImpl.@new();Var input =//…你的参数var myResult = myImplInstance。DoStuff(输入);