元类和构造函数

发布于 2024-11-15 03:27:10 字数 150 浏览 2 评论 0原文

据我了解,在 Smalltalk 和 Objective-C 中创建类的构造函数很困难。这是因为构造函数不能是类实例的消息,因为类 Class 尚未定义。

据我所知,解决方案是创建一个新类,其唯一实例本身就是一个类。但是构造函数在这种情况下如何工作呢?我不明白这个过程。

It is my understanding that it is difficult to create constructors of classes in Smalltalk and Objective-C. This is because the constructor can't be a message of a class instance because the class Class is not yet defined.

As far as I can tell, the solution is to create a new class whose only instance is itself a class. But how does the constructor work in this situation? I don't understand the process.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

没企图 2024-11-22 03:27:10

我说的是 Smalltalk。这里有两种类型的东西可以合理地调用构造函数。一种是初始化类的新实例的方法。另一个是初始化类的东西。两者都不难。

例如初始化,约定是在类上实现“新”方法:
新的
^超级新初始化
(做超类的new实现,然后向结果发送“初始化”消息并返回)
很多类可能已经继承了这个实现,所以你只需要编写一个初始化方法作为

initialize
超级初始化。
富:= 1。
等等。

初始化一个新类,机制类似。您实现一个名为“initialize”的类方法,当该类加载到新的 Smalltalk 环境(图像)时,它将自动发送。

I'm talking in terms of Smalltalk. There are two types of things that you could reasonably call constructors here. One is the method that initializes a new instance of a class. The other is the things that initializes a class. Neither of them is difficult.

For instance initialization, the convention is that you implement the "new" method on the class as
new
^super new initialize
(do the superclass's implementation of new, and then send the "initialize" message to the result and return it)
Lots of classes may already inherit this implementation, so you just need to write an initialize method as

initialize
super initialize.
foo := 1.
etc.

To initialize a new class, the mechanism is similar. You implement a class method called "initialize", and it will automatically get sent when the class is loaded into a new Smalltalk environment (image).

枉心 2024-11-22 03:27:10

解决方案是在类上创建一个方法来完成实例的所有必要初始化。

The solution is to create a method on the class which does all the necessary initialisation of the instance.

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