目前我通过创建它来添加对象:
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;
Run Code Online (Sandbox Code Playgroud)
这种方法是正确还是低效?或者我可以直接添加对象而不是像使用记录一样创建它吗?
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;
Run Code Online (Sandbox Code Playgroud)
还是其他快速而简单的方式?
我使用的是Delphi 7.
提前致谢.
你现在这样做的方式很好.
在向记录添加新记录时,如果没有分配内存,则无法使用记录执行此操作TStringList.Objects
,之后您必须将其释放.就像你现在一样,你也可以选择上课; 你必须在释放stringlist之前释放对象.(在最新版本的Delphi中,TStringList
有一个OwnsObjects
属性可以在stringlist被释放时为你自动释放它们,但它不在Delphi 7中.)
如果你真的想用记录来做这件事,你可以:
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;
Run Code Online (Sandbox Code Playgroud)
System.Dispose(PRec(AList.Objects[i]))
在释放stringlist之前,您需要使用释放内存.正如我所说,你现在这样做的方式实际上要容易得多; 在stringlist中添加和删除时,您不必进行类型转换.
AList.Clear
顺便说一句,你不需要.由于您正在创建字符串列表,因此无法删除任何内容.