dmitrybv 3 Posted August 19 (edited) Should TValue.AsVariant for TBcd type return Custom Variant of TFMTBcdVariantType? Is there a connection between the TFMTBcdVariantType and TValue types. I would like TValue.AsVariant for type TBcd to create a Variant with type TFMTBcdVariantType (TFMTBcdVarData) and return a Custom Variant. Currently this code returns an 'Invalid class typecast' exception. How to correctly check that for a certain 'record' type there is a corresponding Custom Variant type and when calling TValue.AsVariant the creation of the corresponding Custom Variant value is called? Here is a code example: uses System.SysUtils, System.Types, TypInfo, System.UITypes, System.Classes, System.Variants, .... System.Generics.Collections, System.Rtti, Data.FmtBcd, type TListItemObj = class(TPersistent) private FSecondName: String; FFirstName: String; FAge: Integer; FBigUInt: UInt64; FFmtBcd: TBcd; public property FirstName: String read FFirstName write FFirstName; property SecondName: String read FSecondName write FSecondName; property Age: Integer read FAge write FAge; property BigUInt: UInt64 read FBigUInt write FBigUInt; property FmtBcd: TBcd read FFmtBcd write FFmtBcd; end; procedure TForm1.Button1Click(Sender: TObject); var LType: TRttiType; AllProps: TArray<TRttiProperty>; Prop: TRttiProperty; RttiContext: TRttiContext; ValValue: TValue; VarValue: Variant; ListItem: TListItemObj; begin ListItem := TListItemObj.Create; with ListItem do begin FirstName := 'P'; SecondName := 'C'; Age := 33; BigUInt := 12345678900987654321; FmtBcd := 112233445566778899.000011; end; RttiContext := TRttiContext.Create; LType := RttiContext.GetType(TListItemObj); AllProps := LType.GetProperties(); for Prop in AllProps do begin ValValue := Prop.GetValue(ListItem); VarValue := ValValue.AsVariant; end; ListItem.Free; end; Edited August 19 by dmitrybv Share this post Link to post
Remy Lebeau 1392 Posted August 19 (edited) TValue is designed to mimic only conversions that the compiler itself can perform implicitly. Custom variants don't fall into that area. There is no implicit conversions between TBcd and Variant, you have to use explicit function calls (ie VarFMTBcdCreate() and VarToBcd()), which TValue can't call internally for you. That is why you get the 'Invalid class typecast' error. . Edited August 19 by Remy Lebeau Share this post Link to post