擴展TList,限制類型的對象列表
Begin Listing Two - TMyObjectList
TMyObject = class(TObject)
public
procedure DOSomething;
end;
TMyObjectList = class(TObjectList)
protected
function GetItems(Index: Integer): TMyObject;
procedure SetItems(Index: Integer; AMyObject: TMyObject);
public
function Add(aMyObject: TMyObject): Integer;
procedure DOSomething;
function Remove(aMyObject: TMyObject): Integer;
function IndexOf(aMyObject: TMyObject): Integer;
procedure Insert(Index: Integer; aMyObject: TMyObject);
property Items[Index: Integer]: TMyObject
read GetItems write SetItems; default;
end;
...
{ TMyObjectList }
function TMyObjectList.Add(AMyObject: TMyObject): Integer;
begin
Result := inherited Add(AMyObject);
end;
procedure TMyObjectList.DOSomething;
var
i: Integer;
begin
for i := 0 to Count-1 do
Items[i].DOSomething;
end;
function TMyObjectList.GetItems(Index: Integer): TMyObject;
begin
Result := TMyObject(inherited Items[Index]);
end;
function TMyObjectList.IndexOf(AMyObject: TMyObject):
Integer;
begin
Result := inherited IndexOf(AMyObject);
end;
procedure TMyObjectList.Insert(Index: Integer;
AMyObject: TMyObject);
begin
inherited Insert(Index, AMyObject);
end;
function TMyObjectList.Remove(AMyObject: TMyObject):
Integer;
begin
Result := inherited Remove(AMyObject);
end;
procedure TMyObjectList.SetItems(Index: Integer;
AMyObject: TMyObject);
begin
inherited Items[Index] := AMyObject;
end;
End Listing Two