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

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

    Yes this is a problem. But the problem can be solved using record properties:

    type
      TRec = record
      private
        FA : integer;
        FB : string;
        procedure SetA(const Value: Integer);
        procedure SetB(const Value: string);
      public
        property A: Integer read FA write SetA;
        property B: string read FB write SetB;
      end;
    
    procedure TRec.SetA(const Value: Integer);
    begin
      FA := Value;
    end;
    
    procedure TRec.SetB(const Value: string);
    begin
      FB := Value;
    end;
    
    TForm1 = class(TForm)
      Button1: TButton;
      procedure Button1Click(Sender: TObject);
    private
      FRec : TRec;
    public
      property Rec : TRec read FRec write FRec;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Rec.A := 21;
      Rec.B := 'Hi';
    end;
    

    This compiles and workes without problem.

提交回复
热议问题