Pharo 自定义 class 不可索引 (smalltalk)
Pharo custom class is not indexable (smalltalk)
我有以下代码来创建一个集合作为 class 的成员:
CustomClass new members:Set new; yourself.
接下来我要尺寸
custom members size.
这显然是 0,但是当我在集合中插入一个自定义元素并询问大小时,它会导致错误告诉我我的自定义元素不可索引。
custom members add: MyCustomElement new.
custom members size. -> error
这是为什么?如何在 Smalltalk 中解决这一问题?提前致谢
您展示的代码不应触发错误。
但有可能你被#add: 消息咬到了。
#add: 消息 returns 添加的元素,这样你就可以像这样链接添加:
collection2 add: (collection1 add: element).
这也适用于#at:put:
collection2 at: j put: (collection1 at: i put: k).
很像
c2[ j ] = c1[ i ] = k;
不过,如果你这样写:
| s e |
e := MyCustomElement new.
s := (Set new) add: e.
^s size
然后变量 s 将指向与 e 相同的对象,即 MyCustomElement 的实例,而不是新创建的 Set。
以上示例因此将消息 #size 发送到 MyCustomElement 的实例,这听起来很像您描述的错误:这可能会触发错误,因为此 class 的实例不可索引。
您也可以这样写:
(s := Set new) add: e.
或使用通过将#yourself 发送到集合而结束的级联,有效地返回集合本身:
s := (Set new) add: e; yourself.
我有以下代码来创建一个集合作为 class 的成员:
CustomClass new members:Set new; yourself.
接下来我要尺寸
custom members size.
这显然是 0,但是当我在集合中插入一个自定义元素并询问大小时,它会导致错误告诉我我的自定义元素不可索引。
custom members add: MyCustomElement new.
custom members size. -> error
这是为什么?如何在 Smalltalk 中解决这一问题?提前致谢
您展示的代码不应触发错误。
但有可能你被#add: 消息咬到了。
#add: 消息 returns 添加的元素,这样你就可以像这样链接添加:
collection2 add: (collection1 add: element).
这也适用于#at:put:
collection2 at: j put: (collection1 at: i put: k).
很像
c2[ j ] = c1[ i ] = k;
不过,如果你这样写:
| s e |
e := MyCustomElement new.
s := (Set new) add: e.
^s size
然后变量 s 将指向与 e 相同的对象,即 MyCustomElement 的实例,而不是新创建的 Set。
以上示例因此将消息 #size 发送到 MyCustomElement 的实例,这听起来很像您描述的错误:这可能会触发错误,因为此 class 的实例不可索引。
您也可以这样写:
(s := Set new) add: e.
或使用通过将#yourself 发送到集合而结束的级联,有效地返回集合本身:
s := (Set new) add: e; yourself.