简体   繁体   English

我可以直接在stringlist中添加记录作为对象吗?

[英]Can I directly add record as object in stringlist?

Currently I am adding object by creating it like: 目前我通过创建它来添加对象:

type    
  TRecord = class
  private
    str: string;
    num: Integer;
  public
    constructor Create;
  end;

...

procedure TForm1.Button2Click(Sender: TObject);
var
  i: Integer;
  rec: TRecord;
  Alist: TStringList;
begin
  Alist := TStringList.create;
  Alist.Clear;
  for i := 0 to 9 do 
  begin
    rec := Trecord.Create; //create instance of class
    rec.str := 'rec' + IntToStr(i);
    rec.num := i * 2;
    Alist.AddObject(IntToStr(i), rec);
  end;
end;

Is this method correct or inefficient ? 这种方法是正确还是低效? Or Can I directly add object not by creating it like using record? 或者我可以直接添加对象而不是像使用记录一样创建它吗?

type    
  PRec = ^TRec;
  TRec = record
    str: string;
    num: Integer;
  end;

...
var
  rec: TRec;
...

for i := 0 to 9 do 
begin
  //how to write here to have a new record, 
  //can i directly Create record in delphi 7 ?
  rec.str := 'rec' + IntToStr(i);
  rec.num := i*2;
  Alist.AddObject(IntToStr(i), ???); // how to write here?
end;

Or other fast and simple way? 还是其他快速而简单的方式?

I am using Delphi 7. 我使用的是Delphi 7。

Thanks in advance. 提前致谢。

The way you're doing it now is fine. 你现在这样做的方式很好。

You can't do it with a record without allocating memory when you add a new record to the TStringList.Objects , and you'd have to free it afterwards. 在向TStringList.Objects添加新记录时,如果没有分配内存,则无法使用记录执行此操作,之后必须将其释放。 You're just as well off using a class as you are now; 就像你现在一样,你也可以选择上课; you have to free the objects before freeing the stringlist. 你必须在释放stringlist之前释放对象。 (In more recent versions of Delphi, TStringList has an OwnsObjects property that will auto-free them for you when the stringlist is free'd, but it's not in Delphi 7.) (在最新版本的Delphi中, TStringList有一个OwnsObjects属性,当stringlist被释放时会为你自动释放它们,但它不在Delphi 7中。)

If you really want to do this with a record, you can: 如果你真的想用记录来做这件事,你可以:

type    
  PRec = ^TRec;
  TRec = record
    str: string;
    num: Integer;
  end;

var
  rec: PRec;
begin
  for i := 0 to 9 do 
  begin
    System.New(Rec);
    rec.str := 'rec' + IntToStr(i);
    rec.num := i*2;
    Alist.AddObject(IntToStr(i), TObject(Rec)); // how to write here?
  end;
end;

You'll need to use System.Dispose(PRec(AList.Objects[i])) to release the memory before freeing the stringlist. 在释放System.Dispose(PRec(AList.Objects[i]))之前,您需要使用System.Dispose(PRec(AList.Objects[i]))释放内存。 As I said, the way you're doing it now is actually much easier; 正如我所说,你现在这样做的方式实际上要容易得多; you don't have to do the typecast when adding to and deleting from the stringlist. 在stringlist中添加和删除时,您不必进行类型转换。

You don't need the AList.Clear , by the way. AList.Clear ,你不需要AList.Clear Since you're creating the stringlist, there can't be anything in it to remove. 由于您正在创建字符串列表,因此无法删除任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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