首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >精灵类构造

精灵类构造
EN

Stack Overflow用户
提问于 2016-01-10 13:41:56
回答 1查看 162关注 0票数 0

代码将输出

代码语言:javascript
运行
复制
1
2
2

1只打印一次。我不知道怎么用精灵来写。

以下是vala代码:

代码语言:javascript
运行
复制
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");
    }
}

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

如果是精灵的话?(现在)它与vala的类构造不同吗?

妖怪的内脏

下面不能工作!

代码语言:javascript
运行
复制
init
    var a = new One
    var b = new One

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

构造块需要GLib.object 构造块=> init块

但是Vala的类构造了dosen。

所以瓦拉会起作用的,但精灵却不行,

vala代码:

代码语言:javascript
运行
复制
class One {
    class construct {
        stdout.puts("1\n");
    }
    public One () {
        stdout.puts("2\n");
    }
}

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

示例:插入一些静态文件(或类字段:另一个问题)。

我也不知道原因?为什么Vala实现这个特性?如果Vala实现了它,它肯定是有用的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-10 15:44:24

从我认为是init的文档中可以看出什么。虽然我不知道你为什么要用它。对于在类的所有实例中使用的静态数据的延迟加载来说,这可能很有用,但我自己从来没有这样做过。

在面向对象编程术语中,类作为对象创建时被“实例化”。实例化过程可以使用“构造函数”进行定制。在Vala和Genie中,当对象不再需要“析构函数”时,也可以自定义进程。

如果方法不对对象中的数据进行操作,则称为static方法。根据定义,构造函数不对对象中的数据进行操作,而是返回一个新对象。因此,构造函数总是静态的,static construct是错误的名称。在Vala中有class construct,如果您更改代码以使用它,则会得到相同的结果。有关此主题的详细处理,请参阅Vala different type of constructors。关于class construct的部分是在结尾。

我的理解是,Genie的init相当于Vala的class construct。我想你的问题暴露了精灵的一个问题。我的理解是这个代码会回答你的问题:

代码语言:javascript
运行
复制
[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"

然而,这项工作的产出是:

代码语言:javascript
运行
复制
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代码被放置在错误的位置,每次实例化都会被调用,而不是类型注册。所以目前,我不认为在Genie中有类似于Vala的class construct

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34706079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档