为什么attr_accessor创建了一个属性,而method只是一个方法?
我正在研究 C# 和 IronRuby 之间的互操作。我注意到,如果我使用 attr_accessor 在 Ruby 中定义一个属性,它就会作为属性呈现给 C#。另一方面,如果我手动创建完全相同的代码,它会作为方法返回。
例如,采用以下代码:
var engine = IronRuby.Ruby.CreateEngine();
string script = @"
class Test
attr_accessor :automatic
def manual
@manual
end
def manual=(val)
@manual = val
end
def initialize
@automatic = ""testing""
@manual = ""testing""
end
end
Test.new
";
var testObject = engine.Execute(script);
var automatic = testObject.automatic;
var manual = testObject.manual;
当您查看 C# automatic
变量时,该值是一个字符串“testing”。如果您查看 C# manual
变量,它的类型为 IronRuby.Builtins.RubyMethod。
最终,我想在 Ruby 中创建可以在 C# 中使用的自己的属性,但我似乎无法像 attr_accessor
那样使它们像属性一样可见。
我认为,Ruby 源代码的模块代码(ModuleOps.cs:DefineAccessor)中发生了一些神奇的事情。有什么方法可以直接在 Ruby 代码中执行此操作吗?
I am playing around with the interop between C# and IronRuby. I have noticed that if I define a property in Ruby using attr_accessor
, it is presented to C# as a property. If, on the other hand, I create the exact same code manually, it comes back as a method.
For example, take this code:
var engine = IronRuby.Ruby.CreateEngine();
string script = @"
class Test
attr_accessor :automatic
def manual
@manual
end
def manual=(val)
@manual = val
end
def initialize
@automatic = ""testing""
@manual = ""testing""
end
end
Test.new
";
var testObject = engine.Execute(script);
var automatic = testObject.automatic;
var manual = testObject.manual;
When you look at the C# automatic
variable, the value is a string of "testing". If you look at the C# manual
variable, it is type IronRuby.Builtins.RubyMethod.
Ultimately, I want to create my own properties in Ruby that can be used in C#, but I can't seem to make them be visible as properties like attr_accessor
does.
I THINK, that there is some magic going on in the Module code of the Ruby source code (ModuleOps.cs:DefineAccessor). Is there any way to do this in Ruby code directly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个特殊问题在 IronRuby-Core 线程中得到了进一步讨论:
http://rubyforge.org/pipermail/ironruby-core/2010-七月/007154.html
This particular problem was discussed further in the IronRuby-Core thread:
http://rubyforge.org/pipermail/ironruby-core/2010-July/007154.html