Loading and Saving Custom Variant Values
Go Up to Copying and Clearing Custom Variants
By default, when the custom variant is assigned as the value of a published property, it is typecast to a string when that property is saved to a form file, and converted back from a string when the property is read from a form file. You can, however, provide your own mechanism for loading and saving custom variant values in a more natural representation. To do so, the
TCustomVariantType descendant must implement the System.Classes.IVarStreamable interface from Classes.pas.
IVarStreamable defines two methods,
StreamOut, for reading a value of a variant from a stream and for writing the variant's value to the stream. For example,
TComplexVariantType, in the VarCmplx unit, implements the
IVarStreamable methods as follows:
procedure TComplexVariantType.StreamIn(var Dest: TVarData; const Stream: TStream); begin with TReader.Create(Stream, 1024) do try with TComplexVarData(Dest) do begin VComplex := TComplexData.Create; VComplex.Real := ReadFloat; VComplex.Imaginary := ReadFloat; end; finally Free; end; end; procedure TComplexVariantType.StreamOut(const Source: TVarData; const Stream: TStream); begin with TWriter.Create(Stream, 1024) do try with TComplexVarData(Source).VComplex do begin WriteFloat(Real); WriteFloat(Imaginary); end; finally Free; end; end;
Note how these methods create a Reader or Writer object for the
Stream parameter to handle the details of reading or writing values.