【问题标题】:"Property reference" of the class类的“属性参考”
【发布时间】:2022-01-27 07:35:32
【问题描述】:

在 C++Builder 中是否有对类属性的引用,类似于 C++ 中的常规引用?为了理解我的意思,我将给出代码(到目前为止这是我对问题的解决方案):

    void change(TControl* object) {
      struct TAccessor : TControl { __property Text; };
      static_cast<TAccessor*>(object)->Text = L"some text";
    }

此函数允许您更改从 TControl 继承的任何对象的 Text 属性。 但也许这个问题有更优雅的解决方案?

【问题讨论】:

  • 作为一种解决 TControl 不能使 Text 属性可访问的事实的方法(希望 Text 属性可访问的派生类必须明确地这样做)我认为这个解决方案非常优雅。但这真的是你想做的吗?让我觉得有点危险:设计师没有让 Text 可访问可能是有充分理由的......

标签: c++builder


【解决方案1】:

您的方法将更新任何TControlText,即使它实际上并未公开对Text 的访问(在TControl 本身中声明了protected,派生类决定是否提升它根据需要发送至public/__published)。

为了说明这一事实,您必须使用 RTTI 来发现 Text 是否可访问。您也可以使用 RTTI 设置属性值,而无需使用 Accessor 技巧。

例如,旧式 RTTI(通过 &lt;TypInfo.hpp&gt; 标头)仅适用于 __published 属性,没有别的,例如:

#include <TypInfo.hpp>

void change(TControl* object) {
    if (IsPublishedProp(object, _D("Text"))
        SetStrProp(object, _D("Text"), _D("some text"));
}

或者:

#include <TypInfo.hpp>

void change(TControl* object) {
    PPropInfo prop = GetPropInfo(object, _D("Text"), TTypeKinds() << tkUString);
    if (prop)
        SetStrProp(object, prop, _D("some text"));
}

而新式扩展 RTTI(通过 &lt;Rtti.hpp&gt; 标头)支持字段、方法和属性以及所有受支持的成员可见性,例如:

#include <Rtti.hpp>

typedef Set<TMemberVisibility, mvPrivate, mvPublished> TMemberVisibilitySet;

void change(TControl* object) {
    static const TMemberVisibilitySet WantedVisibilities = TMemberVisibilitySet() << mvPublic << mvPublished;
    TRttiContext ctx;
    TRttiType *type = ctx.GetType(object->ClassType());
    TRttiProperty* prop = type->GetProperty(_D("Text"));
    if ((prop) && (WantedVisibilities.Contains(prop->Visibility)) && (prop->IsWritable))
        prop->SetValue(object, _D("some text"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多