我刚刚偶然发现了以下行为。要重现它,请创建一个带有 inst var 的类:
Object subclass: #Asdf
instanceVariableNames: 'countSeq'
classVariableNames: ''
poolDictionaries: ''
category: 'Asdf'
还有一个惰性初始化 getter:
countSeq
^countSeq ifNil: [
countSeq:=#(0) asOrderedCollection.
countSeq at: 1 put: (countSeq at: 1)+1.
countSeq
].
这可以正常工作。当我调用Asdf new countSeq
时然后它返回 an OrderedCollection(1)
每次。
但是,如果我删除 asOrderedCollection
:
countSeq
^countSeq ifNil: [
countSeq:=#(0).
countSeq at: 1 put: (countSeq at: 1)+1.
countSeq
].
并调用Asdf new countSeq
多次,然后我得到 #(1)
, #(2)
, #(3)
....
这该如何解释?
(在我看来,这个数组的行为就像一个 C 静态局部变量。事实上,我尝试了一下:重新编译该方法,不幸的计数器再次从 1 开始)
最佳答案
这是因为文字数组#(0)
存储在方法对象内。
此处解释:Why shouldn't I store into literal arrays in Smalltalk?
关于smalltalk - Squeak Smalltalk 阵列中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225760/