如何将日期时间放入字符串列表对象中?
how can i put a tdatetime into a stringlist object?
我正在尝试使用 Delphi 10.4 Sydney 将 TDateTime
值添加到 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;
我正在尝试使用 Delphi 10.4 Sydney 将 TDateTime
值添加到 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;