GObject样式构造如何工作?

问题描述 投票:1回答:1

我是Vala的新手,正在尝试了解该语言的工作原理。我通常使用Python或JavaScript之类的脚本语言。

所以,我的问题是,为什么有三种方法构造类构造函数,以及GObject样式构造函数如何工作?

为了得到最好的理解,让我们用python做一个类比:

Python类定义

class Car(object):
  speed: int

  def __init__(self, speed): # default constructor
    self.speed = speed # property

和瓦拉

class Car : GLib.Object {
  public int speed { get; construct; }

  // default
  internal Car(int speed) {
    Object(speed: speed)
  }

  construct {} // another way
}

我正在阅读Vala tutorial section about GObject style construction,但仍然不了解Object(speed: speed)的工作原理以及需要什么construct

glib vala
1个回答
1
投票

开发了Vala来替代编写基于GLib的C代码所需的手动工作。

由于C在基于GLib的C代码中没有类,因此以不同于C#或Java的方式构造对象。

这是您的示例代码的valac -C car.vala输出的一部分:

Car*
car_construct (GType object_type,
               gint speed)
{
    Car * self = NULL;
    self = (Car*) g_object_new (object_type, "speed", speed, NULL);
    return self;
}

因此Vala发出一个car_construct函数,该函数调用g_object_new ()方法。这是用于创建任何基于GLib的类的GLib方法,方法是依次传递其类型和名称和值参数来构造参数,并以NULL终止。

[当您不使用construct属性时,将无法通过g_object_new ()传递参数,而您必须调用设置器,例如:

Car*
car_construct (GType object_type,
               gint speed)
{
    Car * self = NULL;
    self = (Car*) g_object_new (object_type, NULL);
    car_set_speed (self, speed);
    return self;
}

此处调用car_set_speed (),而不是通过g_object_new ()传递值。

您更喜欢哪一个取决于一些因素。如果您经常与C代码进行互操作,并且C代码使用构造参数,则希望使用GObject样式构造。否则,您可能对C#/ Java样式的构造函数没问题。

PS:设置程序也由valac自动生成,不仅会设置属性值,还会通过g_object_notify ()系统通知所有侦听器。

© www.soinside.com 2019 - 2024. All rights reserved.