Variant 属性 可以有默认值吗?

Can a Variant property have default value?

我编写了一个具有 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 属性默认值的信息。

变体属性不能有默认值。

注意这里。 default 指令不做任何设置 属性 本身的值。它只影响该值是否显式保存在 .dfm 文件中。如果您为 属性 指定 default 值,您仍然必须确保构造函数将支持字段初始化为该值。

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类型的常量表达式。由于变体是复杂类型,它不能表示为单个常量,因此不能有 default 属性.

Per Remy,如果要确保当支持变体为 False 时变体不保存在 .dfm 文件中,您可以使用 stored 指令和无参数方法 returns 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;

最好的办法是设置

FVariantValue := false;

在构造函数中或procedure AfterConstruction; override;