如果您知道您将在余生中使用 Delphi-7,请坚持使用 TObject(i) 演员表。否则开始使用适当的对象,这将在升级到 64 位时为您省去麻烦。
Unit uSimpleObjects;
Interface
type
TIntObj = class
private
FI: Integer;
public
property I: Integer Read FI;
constructor Create(IValue: Integer);
end;
type
TDateTimeObject = class(TObject)
private
FDT: TDateTime;
public
property DT: TDateTime Read FDT;
constructor Create(DTValue: TDateTime);
end;
Implementation
{ TIntObj }
constructor TIntObj.Create(IValue: Integer);
begin
Inherited Create;
FI := IValue;
end;
{ TDateTimeObject }
constructor TDateTimeObject.Create(DTValue: TDateTime);
begin
Inherited Create;
FDT := DTValue;
end;
end.
用法:
var
IO: TIntObj;
SL: TStringList;
贮存:
SL := TStringList.Create(true); // 'OwnsObjects' for recent Delphi versions
IO := TIntObj.Create(123);
SL.AddObjects(IO);
恢复:
IO := TIntObj(SL.Objects[4]);
ShowMessage('Integer value: '+ IntToStr(IO.I));
对于 Delphi-7
TIntObj := TStringList.Create;
你必须自己释放对象:
for i := 0 to Sl.Count-1 do
begin
IO := TIntObj(SL.Objects[i]);
IO.Free;
end;
SL.Free;