Jump to content
dmitrybv

TValue.AsVariant for TBcd type should return TFMTBcdVariantType?

Recommended Posts

Posted (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 by dmitrybv

Share this post


Link to post
Posted (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 by Remy Lebeau

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×