有没有办法有像虚拟变量的setter /吸气类变量? [英] Is there a way to have class variables with setter/getter like virtual variables?
问题描述
我嵌入到红宝石我的C项目,并希望加载定义从我自己的父类继承的类的几个文件。每个继承类需要设置在初始化一些变量,我不希望有两个不同的变量为Ruby和C。
I am embedding Ruby into my C project and want to load several files that define a class inherited from my own parent class. Each inherited class needs to set some variables on initialization and I don't want to have two different variables for Ruby and C.
有没有一种方法来定义,有一个自定义的setter / getter或这是处理这一个笨方法的类变量?也许这将是一个自定义的数据类型比较好?
Is there a way to define a class variable that has an own custom setter/getter or is this a stupid way to handle it? Maybe it would be better with a custom datatype?
推荐答案
我不知道你问什么。当然,类变量可以有getter和setter方法(和在幕后,你可以存储价值,你喜欢的任何方式)。这是否片断有助于阐明什么?
I'm not sure exactly what you're asking. Of course class variables can have getters and setters (and behind the scenes you can store the value any way you like). Does this snippet help illuminate anything?
>> class TestClass
>> def self.var
>> @@var ||= nil
>> end
>> def self.var=(value)
>> @@var = value
>> end
>> end
=> nil
>>
?> TestClass::var
=> nil
>> TestClass::var = 5
=> 5
>> TestClass::var
=> 5
如果你到整个事情元编程,可以实现类似 attr_accessor中<一class_attr_accessor方法/ A>方法。以下是相当于上面code。
If you're into the whole metaprogramming thing, you can implement a class_attr_accessor method similar to the attr_accessor method. The following is equivalent to the above code.
class Module
def class_attr_accessor(attribute_name)
class_eval <<-CODE
def self.#{attribute_name}
@@#{attribute_name} ||= nil
end
def self.#{attribute_name}=(value)
@@#{attribute_name} = value
end
CODE
end
end
class TestClass
class_attr_accessor :var
end
这篇关于有没有办法有像虚拟变量的setter /吸气类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!