Hier auch noch das Pendant für Components:
Delphi-Quellcode:
type
TComponentHelper = class helper for TComponent
type
TComponentEnumerator<T: TComponent> = class
private
FIndex: Integer;
FComponent: TComponent;
function GetCurrent: T;
public
constructor Create(AComponent: TComponent);
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
IComponents<T: TComponent> = interface
function GetEnumerator: TComponentEnumerator<T>;
end;
TComponents<T: TComponent> = class(TInterfacedObject, IComponents<T>)
private
FComponent: TComponent;
public
constructor Create(AComponent: TComponent);
function GetEnumerator: TComponentEnumerator<T>;
end;
public
function ComponentsOf<T: TComponent>: IComponents<T>;
end;
{ TComponentHelper }
function TComponentHelper.ComponentsOf<T>: IComponents<T>;
begin
Result := TComponents<T>.Create(Self);
end;
{ TComponentHelper.TComponents<T> }
constructor TComponentHelper.TComponents<T>.Create(AComponent: TComponent);
begin
inherited Create;
FComponent := AComponent;
end;
function TComponentHelper.TComponents<T>.GetEnumerator: TComponentEnumerator<T>;
begin
Result := TComponentEnumerator<T>.Create(FComponent);
end;
constructor TComponentHelper.TComponentEnumerator<T>.Create(AComponent: TComponent);
begin
inherited Create;
FComponent := AComponent;
FIndex := -1;
end;
function TComponentHelper.TComponentEnumerator<T>.GetCurrent: T;
begin
Result := FComponent.Components[FIndex] as T;
end;
function TComponentHelper.TComponentEnumerator<T>.MoveNext: Boolean;
begin
repeat
Inc(FIndex);
if FIndex >= FComponent.ComponentCount then
Exit(False);
if FComponent.Components[FIndex] is T then
Exit(True);
until False;
end;