简体   繁体   中英

Cannot assign value to object with array of records

I'm writing a simple object that contain array of records. Just like invoice.(ID,date,customer name and array of records about the items).

type
  Trows = record
  private
    Fcode: string;
    Qty: Double;
    cena: Currency;
    procedure Setcode(const value: string);
  public
    property code: string read Fcode write SetCode;
  end;

  Tcart = class(TObject)
  private
    Frow: array of Trows;
    function  Getrow(Index: Integer): Trows;
    procedure Setrow(Index: Integer; const Value: Trows);
  public
    ID: integer;
    CustName: string;
    Suma: currency;
    Payed: boolean;
    constructor Create(const Num: Integer);
    destructor Destroy;
    function carttostr: string;
    procedure setcode(Index: integer;val: string);
    property Row[Index: Integer]: Trows read Getrow write setrow;
  end;

Everything seems fine since I'm trying to change value of one record. I have found 3 ways to do it. First, and second worked ok, but I'd like to simplify the code modifying the value of this record like this:

cart.row[0].code:='333';

but it doesn't work.

What am I'm missing?

Here is the code:

procedure TForm1.Button1Click(Sender: TObject);
var
  Arows: Trows;
begin
  Cart:=Tcart.Create(0);
  cart.custName:='Customer 1';
  cart.Suma:=5.55;
  cart.Payed:=false;
  Arows.code:='123';
  cart.setrow(0,Arows);  // this way working
  cart.setcode(0,'333');   // this way also working
  cart.row[0].code:='555';      //this way doesn''t change value. How to make it work?
  memo1.Lines.Text:=cart.carttostr;
end;

It doesn't work because your Row[] property returns a TRows record by value , which means the caller receives a copy of the original record. Any modifications you make to the copy are not reflected in the original .

You need to assign the copy back to the property to apply changes:

procedure TForm1.Button1Click(Sender: TObject);
var
  Arows: Trows;
begin
  ...
  Arows := cart.row[0];
  Arows.code:='555';
  cart.row[0] := Arows; // <-- equivalent to 'cart.setrow(0,Arows);'
  ...
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM