它添加了一对项目:TStringList.Strings
列表和匹配的TObject
in the TStringList.Objects
list.
例如,这允许您存储提供项目名称的字符串列表,以及包含匹配项目的类的对象。
type
TPerson=class
FFirstName, FLastName: string;
FDOB: TDateTime;
FID: Integer;
private
function GetDOBAsString: string;
function GetFullName: string;
published
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property DOB: TDateTime read FDOB write FDOB;
property DOBString: string read GetDOBAsString;
property FullName: string read GetFullName;
property ID: Integer read FID write FID;
end;
implementation
{TPerson}
function TPerson.GetDOBAsString: string;
begin
Result := 'Unknown';
if FDOB <> 0 then
Result := DateToStr(FDOB);
end;
function TPerson.GetFullName: string;
begin
Result := FFirstName + ' ' + FLastName; // Or FLastName + ', ' + FFirstName
end;
var
PersonList: TStringList;
Person: TPerson;
i: Integer;
begin
PersonList := TStringList.Create;
try
for i := 0 to 9 do
begin
Person := TPerson.Create;
Person.FirstName := 'John';
Person.LastName := Format('Smith-%d', [i]); // Obviously, 'Smith-1' isn't a common last name.
Person.DOB := Date() - RandRange(1500, 3000); // Make up a date of birth
Person.ID := i;
PersonList.AddObject(Person.LastName, Person);
end;
// Find 'Smith-06'
i := PersonList.IndexOf('Smith-06');
if i > -1 then
begin
Person := TPerson(PersonList.Objects[i]);
ShowMessage(Format('Full Name: %s, ID: %d, DOB: %s',
[Person.FullName, Person.ID, Person.DOBString]));
end;
finally
for i := 0 to PersonList.Count - 1 do
PersonList.Objects[i].Free;
PersonList.Free;
end;
这显然是一个人为的示例,因为它并不是您真正有用的东西。不过,它演示了这个概念。
另一个方便的用途是与字符串一起存储整数值(例如,显示列表中的项目)TComboBox
or TListBox
以及用于数据库查询的相应 ID)。在这种情况下,您只需在中对整数(或任何其他 SizeOf(Pointer))进行类型转换Objects
array.
// Assuming LBox is a TListBox on a form:
while not QryItems.Eof do
begin
LBox.Items.AddObject(QryItem.Fields[0].AsString, TObject(QryItem.Fields[1[.AsInteger));
QryItems.Next;
end;
// User makes selection from LBox
i := LBox.ItemIndex;
if i > -1 then
begin
ID := Integer(LBox.Items.Objects[i]);
QryDetails.ParamByName('ItemID').AsInteger := ID;
// Open query and get info.
end;
存放实际物品以外的物品时TObject
,您不需要释放内容。由于它们不是真实的对象,因此除了TStringList
itself.