gpt4 book ai didi

arrays - 无法为具有记录数组的对象赋值

转载 作者:行者123 更新时间:2023-12-03 18:18:00 26 4
gpt4 key购买 nike

我正在编写一个包含记录数组的简单对象。就像发票一样。(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;

一切似乎都很好,因为我正在尝试更改一条记录的值。我找到了 3 种方法来做到这一点。首先,第二个工作正常,但我想简化修改此记录值的代码,如下所示:

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

但它不起作用。

我错过了什么?

代码如下:

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;

最佳答案

它不起作用,因为您的 Row[] 属性返回一个 TRows 记录按值,这意味着调用者收到一个 原始记录的副本。您对副本所做的任何修改都不会反射(reflect)在原始中。

您需要将副本分配回属性以应用更改:

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;

关于arrays - 无法为具有记录数组的对象赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com