如何将对象的类设置为其他对象?

发布于 2024-08-13 00:01:06 字数 176 浏览 10 评论 0原文

我最近看到了这个,但现在找不到了……

如何将对象的类设置为其他对象?

--更新:嗯,在法罗!就像:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏至、离别 2024-08-20 00:01:06

有#primitiveChangeClassTo:。

它要求原始类和目标类具有相同的类布局。由于某些奇怪的原因,它需要目标类的实例作为参数,但并未使用该实例。

所以你会这样做,

d := Object new.
d primitiveChangeClassTo: Dictionary new.

但是这会失败,因为字典有两个实例变量,但普通对象没有。

如果您热衷于元编程,您可能还会对使用任何对象作为类感兴趣。我在 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

d := Object new.
d primitiveChangeClassTo: Dictionary new.

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.

生死何惧 2024-08-20 00:01:06

方法 #setClass: 在某些特定上下文中使用并具有不同的实现(使用方法查找器检查)。

对象有一些帮助器可以将当前对象转换为其他类型,例如#asOrderedCollection,因为最后一个允许操作:

asOrderedCollection
    "Answer an OrderedCollection with the receiver as its only element."

    ^ OrderedCollection with: self

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:

asOrderedCollection
    "Answer an OrderedCollection with the receiver as its only element."

    ^ OrderedCollection with: self

HTH.

就像说晚安 2024-08-20 00:01:06

好的,那么你可以尝试如下:

d := Object new.
e := Dictionary new.

d become: e. 

但是,请谨慎尝试#become:,因为在很多情况下它会破坏图像。

ok, then you can try something as:

d := Object new.
e := Dictionary new.

d become: e. 

But, please, try #become: with caution, because in lot of situations it break the image.

俏︾媚 2024-08-20 00:01:06

看一下类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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文