RAD Studio |  |

Loading and Saving Custom Variant Values
See Also
Collapse All

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 IVarStreamable interface from Classes.pas.

IVarStreamable defines two methods, StreamIn and StreamOut, for reading a variant's value 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:

Copy Code

    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.

See Also

Implementing Binary Operations

Implementing Comparison Operations

Implementing Unary Operations

Enabling Casting

Copying and Clearing Custom Variants

Using the TCustomVariantType Descendant

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!