如何将对象的类设置为其他对象?
我最近看到了这个,但现在找不到了……
如何将对象的类设置为其他对象?
--更新:嗯,在法罗!就像:
d:=Object new. d setClass: Dictionary.
只是它实际上不是 setClass。如何修改对象的类指针?
I've seen this recently and now I can't find it …
How do you set the class of an object to something else?
--Update: Well, in Pharo! Like:
d:=Object new. d setClass: Dictionary.
Only that it isn't actually setClass. How can you modify the class pointer of an object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有#primitiveChangeClassTo:。
它要求原始类和目标类具有相同的类布局。由于某些奇怪的原因,它需要目标类的实例作为参数,但并未使用该实例。
所以你会这样做,
但是这会失败,因为字典有两个实例变量,但普通对象没有。
如果您热衷于元编程,您可能还会对使用任何对象作为类感兴趣。我在 Protalk 中使用它来实现直接在 Smalltalk 之上工作的基于原型的语言。
There is
#primitiveChangeClassTo:
.It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.
So you would do
however this fails, since dictionaries have two instance variables but plain objects have none.
If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.
方法 #setClass: 在某些特定上下文中使用并具有不同的实现(使用方法查找器检查)。
对象有一些帮助器可以将当前对象转换为其他类型,例如#asOrderedCollection,因为最后一个允许操作:
HTH。
The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).
Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:
HTH.
好的,那么你可以尝试如下:
但是,请谨慎尝试#become:,因为在很多情况下它会破坏图像。
ok, then you can try something as:
But, please, try #become: with caution, because in lot of situations it break the image.
看一下类ClassBuilder。当您修改类时,它会创建一个新类,然后将前者的实例切换为后者的实例。因此它应该提供一些方法来满足您的要求。
Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.