我偶然发现了以下行为。要重现它,请使用inst var:
创建一个类Object subclass: #Asdf
instanceVariableNames: 'countSeq'
classVariableNames: ''
poolDictionaries: ''
category: 'Asdf'
一个懒惰的初学者:
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 :(得分:3)
这是因为文字数组#(0)
存储在方法对象中。
在此解释:Why shouldn't I store into literal arrays in Smalltalk?