“Left side cannot be assigned to” for record type properties in Delphi

前端 未结 8 1003
夕颜
夕颜 2020-12-01 16:09

I\'m curious to know why Delphi treats record type properties as read only:

  TRec = record
    A : integer;
    B : string;
  end;

  TForm1 = class(TForm)
         


        
8条回答
  •  心在旅途
    2020-12-01 16:40

    A solution I frequently use is to declare the property as a pointer to the record.

    type
      PRec = ^TRec;
      TRec = record
        A : integer;
        B : string;
      end;
    
      TForm1 = class(TForm)
      private
        FRec : TRec;
    
        function GetRec: PRec;
        procedure SetRec(Value: PRec);
      public
        property Rec : PRec read GetRec write SetRec; 
      end;
    
    implementation
    
    function TForm1.GetRec: PRec;
    begin
      Result := @FRec;
    end;  
    
    procedure TForm1.SetRec(Value: PRec);
    begin
      FRec := Value^;
    end;
    

    With this, directly assigning Form1.Rec.A := MyInteger will work, but also Form1.Rec := MyRec will work by copying all the values in MyRec to the FRec field as expected.

    The only pitfall here is that when you wish to actually retrieve a copy of the record to work with, you will have to something like MyRec := Form1.Rec^

提交回复
热议问题