M.D*_*rov 2 arrays delphi records assign
我正在写一个包含记录数组的简单对象.就像发票一样.(ID,日期,客户名称和有关物品的记录数组).
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;
Run Code Online (Sandbox Code Playgroud)
一切似乎很好,因为我试图改变一条记录的价值.我找到了3种方法.首先,第二个工作正常,但我想简化修改此记录值的代码,如下所示:
cart.row[0].code:='333';
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
我错过了什么?
这是代码:
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;
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为您的Row[]属性按值返回TRows记录,这意味着调用者会收到原始记录的副本.您对副本所做的任何修改都不会反映在原件中.
您需要将副本分配回属性以应用更改:
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;
Run Code Online (Sandbox Code Playgroud)