在 Smalltalk 中,如何在 class B 的实例上从 Class A 中调用 Class B 中的访问器方法?
In Smalltalk, how do you invoke accessor methods in Class B from within Class A on an instance of class B?
例如,在 class B 中我有 #setValue
和 #getValue
,但我不能在 Class A 中使用它们。我该如何实现?
编辑:
我认为 ClassBInstance setValue:1.
甚至 ClassB ClassBInstance setValue:1.
都行得通。
Object subclass: #Foo
instanceVariableNames: ''
classVariableNames: 'e'
category: 'Example'
使用 ctrl+s 保存
现在通过写入点击生成访问器 Refactoring->Class Var Refactoring->Accessors
然后出现一个框接受它。
转到 class 一侧。修改e方法为
Foo class>>e
e isNil ifTrue: [ self e: 5] .
^e.
接受它。
现在再次定义一个新的 class(记得取消选中 class 侧并转到实例侧)。
Object subclass: #Faa
instanceVariableNames: 'a'
classVariableNames: ''
category: 'Example'
保存这个。
现在再次通过右键单击 class Faa
然后
生成访问器
Refactoring -> Class Refactoring -> Generate Accessors
然后出现一个框接受它。
现在转到 Playground 或 Workspace 运行 这些命令
x := Faa new. "right click on this and select doit"
x a. "right click on this and select print it"
x a: Foo e. "right click on this and select doit"
x a. "right click on this and select print it"
您观察到变量值的差异。
在class中创建一个实例变量
instanceVariableNames: 'binstance'
in class A 创建 initialize
方法(实例端,即不是 class 端)并确保存在以下代码片段
super initialize.
...
bInstance := ClassB new.
现在在 ClassA 中的任何地方(即在任何方法中)使用
bInstance setValue: 'whatever'
要么
myVar := bInstance getValue
BTW 在 Smalltalk 中通常不使用 set 和 get ...它只是
设置值为 value:
getValue 是 value
注意 :
的区别
希望对您有所帮助
例如,在 class B 中我有 #setValue
和 #getValue
,但我不能在 Class A 中使用它们。我该如何实现?
编辑:
我认为 ClassBInstance setValue:1.
甚至 ClassB ClassBInstance setValue:1.
都行得通。
Object subclass: #Foo
instanceVariableNames: ''
classVariableNames: 'e'
category: 'Example'
使用 ctrl+s 保存
现在通过写入点击生成访问器 Refactoring->Class Var Refactoring->Accessors
然后出现一个框接受它。
转到 class 一侧。修改e方法为
Foo class>>e
e isNil ifTrue: [ self e: 5] .
^e.
接受它。
现在再次定义一个新的 class(记得取消选中 class 侧并转到实例侧)。
Object subclass: #Faa
instanceVariableNames: 'a'
classVariableNames: ''
category: 'Example'
保存这个。
现在再次通过右键单击 class Faa
然后
生成访问器
Refactoring -> Class Refactoring -> Generate Accessors
然后出现一个框接受它。
现在转到 Playground 或 Workspace 运行 这些命令
x := Faa new. "right click on this and select doit"
x a. "right click on this and select print it"
x a: Foo e. "right click on this and select doit"
x a. "right click on this and select print it"
您观察到变量值的差异。
在class中创建一个实例变量
instanceVariableNames: 'binstance'
in class A 创建 initialize
方法(实例端,即不是 class 端)并确保存在以下代码片段
super initialize.
...
bInstance := ClassB new.
现在在 ClassA 中的任何地方(即在任何方法中)使用
bInstance setValue: 'whatever'
要么
myVar := bInstance getValue
BTW 在 Smalltalk 中通常不使用 set 和 get ...它只是
设置值为 value:
getValue 是 value
注意 :
希望对您有所帮助