2017-02-10 50 views

回答

5

在这两种形式中创建的对象将是与相同的元件相同类型的和。主要区别在于,在使用Array with:时,每次执行代码时都会得到一个新实例,并且#()可以在方法被接受/编译时创建实例,以便每次执行代码时数组的实例都是一样。

考虑下面的代码:

doSomething 
    array := #(6 7 8). 
    Transcript show: array. 
    array at: 1 put: 3. 

第一次执行DoSomething的一切都会正常。第二次打印3,7,8时,因为该阵列与上次调用方法时修改的 相同。

所以,在使用文字时应该小心,主要是让它们在不会发生突变的情况下使用。

3

考虑的示例类这种方法与实例变量门槛:

Example >> #threshold 
    ^threshold 
Example >> #threshold: anInteger 
    threshold := anInteger 
Example >> #initialize 
    threshold := 0 
Example class >> #new 
    ^super new initialize 

Example >> testArraySum 
    | a | 
    a := #(4 8 10). 
    a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ]. 
    ^a sum 

现在,如果你读testArraySum的代码,如果门槛doesn't变化,它应该始终retunr相同,shouldn'它呢?因为你开始设置一个固定的值,然后减去(或不是,根据阈值,但我们说它是固定的)一个固定的数量,所以它应该是... ... 20.

那么,如果你评估

Example new testArraySum 

几次,你会得到20,18,16 ......因为数组#(4 8 10)被修改。 另一方面,

Example >> testConstantArraySum 
    | a | 
    a := Array new: 3. 
    a at: 1 put: 4; at: 2 put: 8; at: 3 put: 10. 
    a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ]. 
    ^a sum 

是真的不变。

相关问题