【问题标题】:Cannot assign value to object with array of records无法为具有记录数组的对象赋值
【发布时间】:2023-03-25 15:05:01
【问题描述】:

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

【问题讨论】:

    标签: arrays delphi assign records


    【解决方案1】:

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

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

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2012-02-26
      相关资源
      最近更新 更多