我在Smalltalk中有一个类,它存储OrderedCollection对象.每个对象都有一个名称.我想迭代OrderedCollection对象并打印出每个对象的名称.例如,在Java中我会有类似的东西:
for(int i = 0; i < array.length; ++i) {
System.out.println(array[i].getName());
}
Run Code Online (Sandbox Code Playgroud)
这是我在Smalltalk中得到的,其中"list"是OrderedCollection:
1 to: list size do: [
:x | Transcript show: 'The object name:' list at: x printString; cr.
]
Run Code Online (Sandbox Code Playgroud)
您的解决方案很好,除了两个小错误:(1)您忘记了一些括号,(2)连接消息#,丢失:
1 to: list size do: [
:x | Transcript show: 'The object name:' list at: x printString; cr.
]
Run Code Online (Sandbox Code Playgroud)
本来应该
1 to: list size do: [
:x | Transcript show: 'The object name:' , (list at: x) printString; cr.
]
Run Code Online (Sandbox Code Playgroud)
否则Transcript对象将收到#show:at:它不理解的消息.此外,您必须将字符串连接'The object name: '起来(list at: x) printString,这就是您需要#,在其间使用连接消息的原因.
但请注意,在您的示例中,不需要使用索引.而不是迭代1到list size你可以简单地枚举list集合中的对象,如下所示:
list do: [:object | Transcript show: 'The object name: ' , object printString; cr]
Run Code Online (Sandbox Code Playgroud)
此表单通常是首选,因为它避免使用中间索引(x在您的示例中)并强制您x-使用集合访问集合的元素#at:,所有这些都使您的代码更易于阅读和修改.