如何将tdatetime放入stringlist对象?
我正在尝试使用 Delphi 10.4 SydneyTDateTime向TStringList对象中添加一个值。
我设法这样做:
TDateTimeObj = class(TObject)
strict private
DT: TDateTime;
protected
public
constructor Create(FDateTime: TDateTime);
property DateTime: TDateTime read DT write DT;
end;
constructor TDateTimeObj.Create(FDateTime: TDateTime);
begin
Self.DT := FDateTime;
end;
然后我将它添加到TStringList这样的:
procedure TForm1.Button1Click(Sender: TObject);
var
b: TStringList;
begin
b := TStringList.Create;
b.AddObject('a', TDateTimeObj.Create(now));
b.AddObject('b', TDateTimeObj.Create(now));
FreeAndNil(b);
end;
它有效,但是当我关闭程序时,我有内存泄漏,因为我没有释放TDateTimeObj对象。
有没有办法自动释放对象,或者有更好的方法来实现相同的结果?
回答
您必须使字符串列表拥有添加的对象。当字符串列表被销毁时,拥有的对象也会被销毁。
procedure TForm1.Button1Click(Sender: TObject);
var b: TStringList;
begin
b := TStringList.Create(TRUE); // TRUE means OwnObjects
try
b.AddObject('a', TDateTimeObj.Create(now));
b.AddObject('b', TDateTimeObj.Create(now));
finally
FreeAndNil(b); // Owned objects will be destroyed as well
end;
end;
- `FreeAndNil` on a local variableis not needed. Simply using `b.Free;` is more clean.