How to use Delphi RTTI to get and set Record Values

前端 未结 2 584
面向向阳花
面向向阳花 2020-12-25 08:15

I\'m attempting to use the enhanced RTTI features in Delphi XE or later, to read and write objects to XML. So far I\'ve been successful with integers, floats, strings, enum

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-25 08:59

    Attribution: Originally posted as question's updates by the OP (Mitch ) - Migrated as separate answer to improve visibility.

    Barry's solution did the trick. Here's the revised code:

        tkRecord : begin
          subchild := Child.Items.Add ( FProp.Name ) ;
          Value := FProp.GetValue(self) ;
          FRecord := FContext.GetType(FProp.GetValue(self).TypeInfo).AsRecord ;
          for FField in FRecord.GetFields do begin
            Data := FField.GetValue ( Value.GetReferenceToRawData ) ;
            subchild.Items.Add ( FField.Name ).Value := Data.ToString ;
            end;
          end ;
    

    For those that need to deal with arrays:

        tkDynArray : begin
          Value := FProp.GetValue ( self ) ;
          FArray := FContext.GetType(Value.TypeInfo) as TRttiDynamicArrayType ;
          subchild := child.Items.Add ( FProp.Name ) ;
          cnt := Value.GetArrayLength ;
          subchild.Properties.Add ( 'Count' , cnt ) ;
          case FArray.ElementType.TypeKind of
            tkInteger ,
            tkFloat   : begin
              for a := 0 to cnt-1 do begin
                Data := Value.GetArrayElement ( a ) ;
                subchild.Items.Add ( IntToStr(a) , Data.ToString ) ;
                end;
              end ;
            tkRecord  : begin
              FRecord := FArray.ElementType as TRttiRecordType ;
              for a := 0 to cnt-1 do begin
                Data := Value.GetArrayElement ( a ) ;
                subsubchild := subchild.Items.Add ( IntToStr(a) ) ;
                for FField in FRecord.GetFields do
                  SaveField ( subsubchild , FContext , FField , Data.GetReferenceToRawData ) ;
                end;
              end ;
    

提交回复
热议问题