使用不是GObject属性的参数初始化GObject吗

使用不是GObject属性的参数初始化GObject吗

本文介绍了使用不是GObject属性的参数初始化GObject吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

  • 具有AB继承.然后A自动具有B的所有属性.
  • 不要在A中使用属性,而是将B的属性(甚至更好的是,已经构造好的B对象)作为参数传递给A的构造函数.
  • B的延迟构造,直到A可以弄清楚如何配置B.在Ab_initialized或其他内容中添加一个私有标志,以告诉您A指向B的内部指针是否有效.
    • Have A inherit from B. Then A has all of B's properties automatically.
    • Don't use properties in A, but instead pass B's properties (or even better, an already-constructed B object) as parameters to A's constructor.
    • Delay construction of B until A can figure out how it nees to configure B. Add a private flag to A, b_initialized or something, that tells you whether A's internal pointer to B 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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:43