问题描述
我是Vala的新手,正试图了解该语言的工作原理.我通常使用Python或JavaScript之类的脚本语言.
I'm new to Vala and trying to understand how the language works. I usually use script languages like Python or JavaScript.
所以,我的问题是为什么要使用三种方式构造类构造函数,以及GObject样式构造函数如何工作?
So, my question is why are there three ways of class constructor definition and how does the GObject style constructor work?
为了最好的理解,让我们用python做一个比喻:
For the best understanding lets make an analogy with 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
}
我正在阅读关于GObject样式构造的Vala教程部分 ,但仍然不了解Object(speed: speed)
的工作原理和construct
的需求是什么?
I was reading the Vala tutorial section about GObject style construction, but still do not understand how Object(speed: speed)
works and for what construct
is needed?
推荐答案
开发了Vala来替代编写基于GLib的C代码所需的手动工作.
Vala was developed as a replacement for the manual effort needed to write GLib based C code.
由于C在基于GLib的C中没有类,因此以不同于C#或Java的方式来构造对象.
Since C has no classes in GLib based C code object construction is done in a different way than in say C# or Java.
以下是您的示例代码valac -C car.vala
输出的一部分:
Here is a fragment of the output of valac -C car.vala
for your example code:
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终止.
So Vala emits a car_construct
function that calls the g_object_new ()
method. This is the GLib method used to create any GLib based class, by passing its type and construct parameters by name and value arguments one after another, terminated by NULL.
当您不使用construct
属性时,将无法通过g_object_new ()
传递参数,而您必须调用设置器,例如:
When you don't use construct
properties it won't be possible to pass parameters via g_object_new ()
and you'd have to call the setter, for example:
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 ()
传递值.
Here car_set_speed ()
is called instead of passing the value via g_object_new ()
.
您更喜欢哪一个取决于一些因素.如果您经常与C代码进行互操作,并且C代码使用构造参数,则希望使用GObject样式构造.否则,您可能对C#/Java样式的构造函数没问题.
Which one you prefer depends on a few factors. If you do interop with C code often and the C code uses construct parameters, you want to use GObject style construction. Otherwise you are probably fine with the C#/Java style constructors.
PS:设置程序也由valac自动生成,不仅会设置属性值,还会通过g_object_notify ()
系统通知所有侦听器.
PS: The setter is also auto generated by valac and will not only set the property value, but notify any listeners through the g_object_notify ()
system.
这篇关于GObject样式构造如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!