gpt4 book ai didi

c# - 在 IronRuby 中包含接口(interface)的问题

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:50 25 4
gpt4 key购买 nike

我有一个看起来像这样的界面:

interface IMyInterface {
MyObject DoStuff(MyObject o);
}

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

但是当我尝试做类似的事情时

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 支持通过将接口(interface)混合到类中来实现接口(interface)。

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

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

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

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

下面显示了您可以通过调用接口(interface)上的方法从 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());
}
}

关于c# - 在 IronRuby 中包含接口(interface)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8715005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com