普通口齿不清
我将状态定义为绑定到向量的特殊变量的数量。因此,分配给特殊变量会更改状态。
(defgeneric state (object)
(:documentation "Get the state of this object."))
(defmethod state ((object vector))
;; The state of a vector is the number of symbols bound to it.
(let ((count 0))
;; Iterate each SYM, return COUNT.
(do-all-symbols (sym count)
;; When SYM is bound to this vector, increment COUNT.
(when (and (boundp sym) (eq (symbol-value sym) object))
(incf count)))))
(defparameter *a* #(this is a vector))
(defparameter *b* nil)
(defparameter *c* nil)
(print (state *a*))
(setf *b* *a*)
(print (state *a*))
(print (state *a*))
(setf *c* *a*)
(print (state *a*))
输出:
1
2
2
3
它仅适用于对特殊变量的赋值,不适用于词法变量,也不适用于对象内的插槽。
当心 do-all-symbols
它会出现在所有程序包中,因此会丢失没有程序包的变量。它可能会重复计算多个软件包中存在的符号(当一个软件包从另一软件包中导入符号时)。
红宝石
Ruby几乎相同,但是我将状态定义为引用数组的常量的数量。
class Array
# Get the state of this object.
def state
# The state of an array is the number of constants in modules
# where the constants refer to this array.
ObjectSpace.each_object(Module).inject(0) {|count, mod|
count + mod.constants(false).count {|sym|
begin
mod.const_get(sym, false).equal?(self)
rescue NameError
false
end
}
}
end
end
A = %i[this is an array]
puts A.state
B = A
puts A.state
puts A.state
C = A
puts A.state
输出:
state-assign.rb:9:in `const_get': Use RbConfig instead of obsolete and deprecated Config.
1
2
2
3
这是histocrat对不是类或模块的Ruby对象的回答的概括。出现警告是因为Config常量自动加载了发出警告的某些代码。
LValue = obj
行state
才能实际更改吗?(我可以在C#中创建一个属性,每次获得它就会增加)