从我认为是的文档中可以看出init
。虽然我不确定你为什么要使用它。它对于类的所有实例中使用的静态数据的一些延迟加载可能很有用,但我自己从来没有这样做过。
在面向对象的编程术语中,一个类在创建为对象时被“实例化”。可以使用“构造函数”自定义实例化过程。在 Vala 和 Genie 中,当不再需要某个对象时,还可以使用“析构函数”来自定义该过程。
如果方法不作用于对象中的数据,则称为static
方法。根据定义,构造函数不会作用于对象中的数据,而是返回一个新对象。所以构造函数总是静态的并且static construct
是错误的名称。在 Vala 中class construct
,如果您更改代码以使用它,您将获得相同的结果。请参阅Vala 不同类型的构造函数,以在 Vala 中对这个主题进行彻底的处理。关于的部分class construct
在最后。
我的理解是 Genie 的init
相当于 Vala 的class construct
。我认为您的问题在 Genie 中发现了一个问题。我的理解是这段代码会回答你的问题:
[indent = 4]
init
var a = new One()
var b = new One()
var c = new One.alternative_constructor()
class One:Object
init
print "Class 'One' is registered with GType"
construct()
print "Object of type 'One' created"
construct alternative_constructor()
print """Obect of type 'One' created with named constructor
'alternative_constructor', but the design of your
class is probably too complex if it has multiple
constructors."""
def One()
print "This is not a constructor"
final
print "Object of type 'One' destroyed"
但是,这会输出:
Class 'One' is registered with GType
Object of type 'One' created
Class 'One' is registered with GType
Object of type 'One' created
Class 'One' is registered with GType
Obect of type 'One' created with named constructor
'alternative_constructor', but the design of your
class is probably too complex if it has multiple
constructors.
Object of type 'One' destroyed
Object of type 'One' destroyed
Object of type 'One' destroyed
而使用 GType 的注册只发生一次,因此init
代码被放置在错误的位置,并且在每次实例化时都被调用,而不是类型注册。所以目前我认为class construct
Genie 中没有与 Vala 相当的东西。
改变的行为init
可能是一种解决方案,但我可能误解了它的最初目的,现在可能有很多代码依赖于它当前的行为。另一种解决方案是为实现此功能的 Genie 解析器编写一个补丁。您需要说明为什么此功能有用。