Can the Variant property have a default value?

I wrote a component that has a Variant property for which I would like to set a default value.

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

When compiling, I get the following error in the VariantValue properties:

E2026 Constant expression expected.

The same with the Boolean property does not cause any errors.

I read some documentation, but I did not find anything about the default values ​​of the Variant properties.

+5
source share
3 answers

Be careful. The default directive does nothing to set the value of the property itself. This only affects whether the value is explicitly stored in the .dfm file. If you specify a default value for a property, you should still make sure that the constructor initializes the support field for this value.

Properties: Storage Specifications

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

Note Property values ​​are not automatically initialized to the default value. That is, the default directive only controls when property values ​​are stored in the form file, but not the initial property value in the newly created instance.

This is just a hint at a component streaming system that does not need to be stored in .dfm β€” your part of the contract is for you to actually initialize the support field for that value. The appropriate place to initialize this type is the component constructor:

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

However, False is logical and not an option, so it cannot be used as a constant expression of type Variant . Since the variant is a complex type, it cannot be expressed as a single constant and, therefore, cannot have the default property.

Per Remy, if you want to make sure that the option is not saved in the .dfm file, if the support option is False , you can use the stored directive with a parameter without parameters, which returns False when the option is set to boolean False . For instance:

  property VariantValue : Variant read FVariantValue write FVariantValue stored IsVariantValueStored; 

Where

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

Variant properties cannot have default values.

+4
source

Best set

 FVariantValue := false; 

in the constructor or procedure AfterConstruction; override; procedure AfterConstruction; override;

+1
source

Source: https://habr.com/ru/post/1266697/


All Articles