如何引用从 IronRuby 添加到 ScriptScope 的变量?

发布于 2024-10-22 04:38:53 字数 516 浏览 0 评论 0原文

我正在尝试将变量添加到作用域,然后从我的 ruby​​ 表达式访问该变量。

时间:2019-03-17 标签:c#

ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime();
var scope = runtime.ExecuteFile("C:\\codebase\\Test\\Test2\\Test2\\person2.rb");
scope.SetVariable("name", "Scott");
dynamic person = scope.Engine.Execute("p = Person.new(name)");
person.sayHi();

Ruby

class Person
   def initialize(name)
      @name = name.capitalize
   end
   def sayHi
      puts "Hello #{@name}!"
   end
end

I'm trying to add a Variable to the scope and then access that variable from my ruby expression.

c#

ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime();
var scope = runtime.ExecuteFile("C:\\codebase\\Test\\Test2\\Test2\\person2.rb");
scope.SetVariable("name", "Scott");
dynamic person = scope.Engine.Execute("p = Person.new(name)");
person.sayHi();

Ruby

class Person
   def initialize(name)
      @name = name.capitalize
   end
   def sayHi
      puts "Hello #{@name}!"
   end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

焚却相思 2024-10-29 04:38:53

你们非常接近。只需将 C# 代码的最后两行更改为下一行:

dynamic p = scope.Engine.Execute("Person.new(name)", scope);
p.sayHi();

此外,虽然我不确定您要实现什么目标,但您可以以更简单的方式使用 C# 中的类:

var engine = Ruby.CreateEngine();
var scope = engine.ExecuteFile(@"C:\codebase\Test\Test2\Test2\person2.rb");

dynamic globalConstants = engine.Runtime.Globals;
dynamic person = globalConstants.Person.@new("shay");
person.sayHi();

You were pretty close. Just change the last two lines of your C# code to the next ones:

dynamic p = scope.Engine.Execute("Person.new(name)", scope);
p.sayHi();

In addition, though I'm not sure what you're trying to achieve, you can use your class from C# in an easier fashion:

var engine = Ruby.CreateEngine();
var scope = engine.ExecuteFile(@"C:\codebase\Test\Test2\Test2\person2.rb");

dynamic globalConstants = engine.Runtime.Globals;
dynamic person = globalConstants.Person.@new("shay");
person.sayHi();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文