问题描述
我有一个GObject"A",它在其构造函数中创建了另一个GObject"B"的实例.
I have a GObject "A" which creates an instance of another GObject "B" in its constructor.
"B"对象需要传递几个仅用于构造的属性.现在,当创建对象"A"的实例时,我想允许这些属性的值通过对象"A"的构造函数传递到对象"B"的构造函数.
The "B" object needs to be passed several construction-only properties. Now when creating an instance of object "A" I want to allow passing values for these properties through the constructor of object "A" on to the constructor of object "B".
我发现这样做的唯一方法是为对象"A"创建相同的属性,并将其值传递给"B"的构造函数.这些属性对"A"没有任何进一步的含义,因此这似乎有点矛盾.
The only way I have found to do that was to create identical properties for object "A" and pass their values on to the constructor of "B". These properties would have no further meaning to "A" so this seems like a kludge.
是否有更好的方法来做我想做的事?
Is there a better way to do what I want?
推荐答案
- 具有
A
从B
继承.然后A
自动具有B
的所有属性. - 不要在
A
中使用属性,而是将B
的属性(甚至更好的是,已经构造好的B
对象)作为参数传递给A
的构造函数. -
B
的延迟构造,直到A
可以弄清楚如何配置B
.在A
,b_initialized
或其他内容中添加一个私有标志,以告诉您A
指向B
的内部指针是否有效. - Have
A
inherit fromB
. ThenA
has all ofB
's properties automatically. - Don't use properties in
A
, but instead passB
's properties (or even better, an already-constructedB
object) as parameters toA
's constructor. - Delay construction of
B
untilA
can figure out how it nees to configureB
. Add a private flag toA
,b_initialized
or something, that tells you whetherA
's internal pointer toB
is valid.
关于第二个建议的更多说明:
Some more clarification on the second suggestion:
A
的内容是由G_DEFINE_TYPE()
宏提供的a_init()
函数构造的.但这不是获取A
实例的方式.通常编写一个函数,该函数是A
的公共接口的一部分,如下所示:
A
's stuff is constructed in the a_init()
function that is provided for by the G_DEFINE_TYPE()
macro. But that's not how you get an instance of A
. It's usual to write a function, which is part of the public interface of A
, like this:
A *a_new()
{
return (A *)g_object_new(TYPE_A, NULL);
}
您可以轻松地将其扩展为包括其他参数:
You can easily extend this to include other parameters:
A *a_new(int b_param_1, int b_param_2)
{
A *a = (A *)g_object_new(TYPE_A, NULL);
a->priv->b = b_new(b_param_1, b_param_2);
return a;
}
这样的缺点是,如果使用g_object_new
构造A
对象(例如,没有B
),则该对象处于无效状态(例如,如果您尝试从GtkBuilder文件构建它) .如果存在问题,我仍然强烈建议您进行重构.
This has the disadvantage of leaving your A
object in an invalid state (i.e., without a B
) if you construct it using g_object_new
, for example if you're trying to build it from a GtkBuilder file. If that's a problem, I still strongly suggest refactoring.
这篇关于使用不是GObject属性的参数初始化GObject吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!