我编写了以下 Ruby 代码文件:
require 'MyAssembly.dll'
class MyClass
def initialize(obj)
System::Diagnostics::WriteLine('test')
@var = MyAssembly::Namespace::CSharpClass.new
end
end
MyClass
CSharpClass 是一个具有一个默认构造函数的类。现在,我像这样处理这个文件:
dynamic MyClass = RubyEngine.Execute(script)
//script is a string which contains the aforementioned Ruby code as text
MyClass.@new(some_obj)
请注意,MyClass 有一个带有一个参数的构造函数。当我运行程序时,我得到以下异常: ArgumentException - 最后一个 C# 代码行的参数数量错误(0 代表 1)。
如果我将 CSharpClass 更改为任何其他名称,则会有一个异常说我没有这样的对象(所以我猜测程序集加载工作正常)。
现在有趣的部分:如果我将 initialize(obj) 方法中的第二行更改为
@var = MyAssembly::Namespace::CSharpClass.new(nil)
然后在调试输出中有一长串“测试”字符串和一个 StackOverflowException。所以它看起来像递归 MyClass 对象实例化,即 CSharpClass.new(nil) 以某种方式执行为 MyClass.new(nil)。可能这就是我得到上面的 AgrumentException 的原因。
我已经尝试过 IronRuby 1.0 和 1.1.3 但无济于事。我错过了什么?
更新
更多乐趣!现在假设 Ruby 代码如下所示:
require 'MyAssembly.dll'
class MyClass
def initialize(a, b)
@var = MyAssembly::Namespace::CSharpClass.new
end
end
MyClass.new(0, 0)
如果我尝试使用不同的参数调用 CSharpClass.new,我会收到互斥的异常消息:
CSharpClass.new # wrong number of arguments (0 for 1)
CSharpClass.new(0) # wrong number of arguments (1 for 2)
CSharpClass.new(0, 0) # wrong number of arguments (2 for 1)
...
CSharpClass.new(<N args>) # wrong number of arguments (N for 1)
如果有人知道我做错了什么,我会很高兴——我真的很想在我的项目中使用 IronRuby。