簡體   English   中英

在Smalltalk中,如何在類B的實例上從類A內調用類B中的訪問器方法?

[英]In Smalltalk, how do you invoke accessor methods in Class B from within Class A on an instance of class B?

例如,在BI類中具有#setValue#getValue ,但是我不能在A類中使用它們。如何實現此目的?

編輯:

我認為可以的將是ClassBInstance setValue:1. 甚至ClassB ClassBInstance setValue:1. 但兩者都不是。

在類A中創建一個實例變量,說instanceVariableNames: 'binstance'

在類A中,創建initialize方法(實例端,即不是類端),並確保以下代碼片段在那里具有super initialize. ... bInstance := ClassB new. super initialize. ... bInstance := ClassB new.

現在,在ClassA中的任何位置(即,以任何方法)都可以使用bInstance setValue: 'whatever'myVar := bInstance getValue

按慣例,Smalltalk中的BTW不會設置和獲取...它的簡單setValue是value: getValue是value note的區別:

希望能幫助到你

Object subclass: #Foo  
    instanceVariableNames: ''  
    classVariableNames: 'e'  
    category: 'Example'

使用ctrl + s保存

現在可以通過單擊寫入,然后單擊Refactoring->Class Var Refactoring->Accessors生成訪問器,然后出現一個接受它的框。
去上課。 將e方法修改為

Foo class>>e  
    e  isNil ifTrue: [ self e: 5] .  
    ^e.  

接受。
現在再次定義一個新類(記住取消選中類端並轉到實例端)。

Object subclass: #Faa  
    instanceVariableNames: 'a'  
    classVariableNames: ''  
    category: 'Example' 

保存這個。
現在再次通過右鍵單擊類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"  

您會觀察到變量值的差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM