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

前端 未结 8 1008
夕颜
夕颜 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:52

    Like others have said - the read property will return a copy of the record, so the assignment of fields isn't acting on the copy owned by TForm1.

    Another option is something like:

      TRec = record
        A : integer;
        B : string;
      end;
      PRec = ^TRec;
    
      TForm1 = class(TForm)
      private
        FRec : PRec;
      public
        constructor Create;
        destructor Destroy; override;
    
        procedure DoSomething(ARec: TRec);
        property Rec : PRec read FRec; 
      end;
    
    constructor TForm1.Create;
    begin
      inherited;
      FRec := AllocMem(sizeof(TRec));
    end;
    
    destructor TForm1.Destroy;
    begin
      FreeMem(FRec);
    
      inherited;
    end;
    

    Delphi will dereference the PRec pointer for you, so things like this will still work:

    Form1.Rec.A := 1234; 
    

    There's no need for a write part of the property, unless you want to swap the PRec buffer that FRec points at. I really wouldn't suggest to do such swapping via a property anyway.

提交回复
热议问题