So, hier noch eine generische Alternative wenn es auf Performance nicht ganz so ankommt (wegen der anonymen Methode). Kann man dann allerdings auch leicht in anderen Situationen einsetzen.
Delphi-Quellcode:
type
TEnumWrapper<T: class> = record
type
TGetItemFunc = TFunc<Integer, TObject>;
TEnumerator = record
private
FIndex: Integer;
FCount: Integer;
FCurrent: T;
FGetItem: TGetItemFunc;
public
function MoveNext: Boolean; inline;
property Current: T read FCurrent;
end;
private
FCount: Integer;
FGetItem: TGetItemFunc;
public
constructor Create(ACount: Integer; AGetItem: TGetItemFunc);
function GetEnumerator: TEnumerator; inline;
end;
type
TComponentHelper = class helper for TComponent
public
function ComponentsOf<T: TComponent>: TEnumWrapper<T>; inline;
end;
type
TWinControlHelper = class helper for TWinControl
public
function ControlsOf<T: TControl>: TEnumWrapper<T>; inline;
end;
implementation
{ TEnumWrapper<T> }
constructor TEnumWrapper<T>.Create(ACount: Integer; AGetItem: TGetItemFunc);
begin
FCount := ACount;
FGetItem := AGetItem;
end;
function TEnumWrapper<T>.GetEnumerator: TEnumerator;
begin
Result.FCount := FCount;
Result.FGetItem := FGetItem;
Result.FIndex := -1;
end;
function TEnumWrapper<T>.TEnumerator.MoveNext: Boolean;
var
cmp: TObject;
begin
repeat
Inc(FIndex);
if FIndex < FCount then
begin
cmp := FGetItem(FIndex);
if cmp.InheritsFrom(T) then
begin
FCurrent := T(cmp);
Exit(True);
end;
Continue;
end;
until True;
Result := False;
end;
{ TComponentHelper }
function TComponentHelper.ComponentsOf<T>: TEnumWrapper<T>;
begin
Result := TEnumWrapper<T>.Create(ComponentCount,
function(Index: Integer): TObject
begin
Result := Components[Index];
end);
end;
{ TWinControlHelper }
function TWinControlHelper.ControlsOf<T>: TEnumWrapper<T>;
begin
Result := TEnumWrapper<T>.Create(ControlCount,
function(Index: Integer): TObject
begin
Result := Controls[Index];
end);
end;