我正在使用 IronRuby 并试图弄清楚如何使用带有 C# 方法的块。
这是我试图模拟的基本 Ruby 代码:
def BlockTest ()
result = yield("hello")
puts result
end
BlockTest { |x| x + " world" }
我尝试用 C# 和 IronRuby 做同样的事情是:
string scriptText = "csharp.BlockTest { |arg| arg + 'world'}\n";
ScriptEngine scriptEngine = Ruby.CreateEngine();
ScriptScope scriptScope = scriptEngine.CreateScope();
scriptScope.SetVariable("csharp", new BlockTestClass());
scriptEngine.Execute(scriptText, scriptScope);
BlockTestClass 是:
public class BlockTestClass
{
public void BlockTest(Func<string, string> block)
{
Console.WriteLine(block("hello "));
}
}
当我运行 C# 代码时,出现以下异常:
参数数量错误(0 代表 1)
如果我将 IronRuby 脚本更改为以下内容,它将起作用。
string scriptText = "csharp.BlockTest lambda { |arg| arg + 'world'}\n";
但是我如何让它与原始 IronRuby 脚本一起工作,以便它等同于我原始的 Ruby 示例?
string scriptText = "csharp.BlockTest { |arg| arg + 'world'}\n";