0

代码将输出

1
2
2

1只打印一次。我不知道如何在 genie 中编写它。

下面是vala代码:

public static void main() {
    var a = new One();
    var b = new One();
}

class One : Object {
    class construct {
        stdout.puts("1\n");
    }
    public One () {
        stdout.puts("2\n");
    }
}

genie的等效代码 类构造方法是什么?

如果精灵的初始化?(现在)它与 vala 的类构造不同吗?

精灵的初始化

下面不能工作!

init
    var a = new One
    var b = new One

class One
    construct ()
        stdout.puts("2\n")
    init
        stdout.puts("1\n")

构造块需要 GLib.object

构造块 => 初始化块

但是 Vala 的类结构没有。

所以 vala 会起作用,但 Genie 不会,

验证码:

class One {
    class construct {
        stdout.puts("1\n");
    }
    public One () {
        stdout.puts("2\n");
    }
}

为什么这个功能有用? 实际上,我以前从未使用过课程。但我认为它很有用,非常有用。

例如:初始化一些静态文件(或类字段:另一个问题)。

我不知道为什么?为什么 Vala 实现这个功能?如果 Vala 实现它,它一定很有用。

4

1 回答 1

2

从我认为是的文档中可以看出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 constructGenie 中没有与 Vala 相当的东西。

改变的行为init可能是一种解决方案,但我可能误解了它的最初目的,现在可能有很多代码依赖于它当前的行为。另一种解决方案是为实现此功能的 Genie 解析器编写一个补丁。您需要说明为什么此功能有用。

于 2016-01-10T15:44:24.367 回答