元类和构造函数
据我了解,在 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我说的是 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).
解决方案是在类上创建一个方法来完成实例的所有必要初始化。
The solution is to create a method on the class which does all the necessary initialisation of the instance.