如何覆盖数组的打印?

时间:2019-03-06 12:43:19

标签: pharo

printOn: aStream
    | normalized |
    normalized := self normalized.
    aStream nextPut: ${.
    self isEmpty ifFalse: [ 
        normalized printElem: 1 on: aStream.
        2 to: self size do: [ :i | 
            aStream nextPutAll: ' . '.
            normalized printElem: i on: aStream 
            ].
        ].
    aStream nextPut: $}

printOn:方法有效,但检查器正在使用其他某种途径来打印阵列。如何告诉Inspector对从Array继承的类使用以上方法?

1 个答案:

答案 0 :(得分:3)

检查器使用gtDisplayOn:表示对象。

Object中,它实现为:

gtDisplayOn: stream
    "This offers a means to customize how the object is shown in the inspector"
    ^ self printOn: stream

但是,Collection将其覆盖为:

gtDisplayOn: stream
    self printNameOn: stream.
    stream
        space;
        nextPut: $[;
        print: self size;
        nextPutAll: (' item' asPluralBasedOn: self size);
        nextPut: $];
        space.
    self size <= self gtCollectionSizeThreshold 
        ifTrue: [ self printElementsOn: stream ]

只需在类中再次覆盖它即可像printOn:一样使用Object