加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – Variant属性可以有默认值吗?

发布时间:2020-12-15 09:49:25 所属栏目:大数据 来源:网络整理
导读:我编写了一个具有Variant属性的组件,我想为其设置一个默认值. TMyComponent = class(TComponent)private FVariantValue : Variant;published property VariantValue : Variant read FVariantValue write FVariantValue default False;end; 在编译时,我在Vari
我编写了一个具有Variant属性的组件,我想为其设置一个默认值.

TMyComponent = class(TComponent)
private
  FVariantValue : Variant;
published
  property VariantValue : Variant read FVariantValue write FVariantValue default False;
end;

在编译时,我在VariantValue属性行上收到以下错误:

E2026 Constant expression expected

使用Boolean属性执行相同操作不会导致任何类型的错误.

我读了一点documentation,但我没有发现Variant属性的默认值.

解决方法

这里要小心.默认指令不执行任何操作来设置属性本身的值.它仅影响值是否显式保存在.dfm文件中.如果为属性指定默认值,则仍必须确保构造函数将支持字段初始化为该值.

Properties : Storage Specifiers

When saving a component’s state,the storage specifiers of the component’s published properties are checked. If a property’s current value is different from its default value (or if there is no default value) and the stored specifier is True,then the property’s value is saved. Otherwise,the property’s value is not saved.

Note: Property values are not automatically initialized to the default value. That is,the default directive controls only when property values are saved to the form file,but not the initial value of the property on a newly created instance.

这只是组件流系统的一个提示,它不需要在.dfm中显式存储该值 – 您的合同部分是确保您实际将支持字段初始化为该值.进行此类初始化的适当位置是在组件的构造函数中:

constructor TMyComponent.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FVariantValue := False;
end;

也就是说,False是布尔值,而不是变量,因此它不能用作Variant类型的常量表达式.由于变体是复杂类型,因此不能将其表示为单个常量,因此不能具有默认属性.

Per Remy,如果要在后备变量为False时确保变量未保存在.dfm文件中,则可以使用带有无参数方法的stored指令,当变量求值为布尔值False时,该方法返回False.例如 :

property VariantValue : Variant read FVariantValue write FVariantValue stored IsVariantValueStored;

哪里

function TMyComponent.IsVariantValueStored : Boolean;
begin
  Result := not VarIsType(FVariantValue,varBoolean);
  if not Result then
    Result := FVariantValue;
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读