Playing with generics, code to filter items of a given class, using an anonymous procedure. (Already saw FMX.Types TEnumerableFilter used in TListBox, but wanted to do something different).
Playing with generics, code to filter items of a given class, using an anonymous procedure. (Already saw FMX.Types TEnumerableFilter used in TListBox, but wanted to do something different).
For example if you have a Form or Control and you want to do something only with its TButton children controls:
uses MyFilter;
// FireMonkey:
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
TEnumerableFilter(Children).Find(procedure(Sender:TButton)
begin
Sender.Visible:=CheckBox1.IsChecked;
end);
end;
// VCL:
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
Find(procedure(Sender:TButton)
begin
Sender.Visible:=CheckBox1.Checked;
end);
end;
(The VCL version is a proper "class helper", as its not possible to create class helpers for generic types).
The code for FireMonkey:
uses
System.Generics.Collections;
type
TFindProc=reference to procedure(Sender:F);
TEnumerableFilter=class(TEnumerable)
public
procedure Find(const AProc:TFindProc);
end;
procedure TEnumerableFilter.Find(const AProc:TFindProc);
var Item : T;
begin
for Item in Self do
if Item is T then
AProc(Item as T);
end;
The code for VCL:
uses VCL.Controls;
type
TFindProc=reference to procedure(Sender:F);
TVCLEnumerableFilter=class helper for TWinControl
public
procedure Find(const AProc:TFindProc);
end;
procedure TVCLEnumerableFilter.Find(const AProc:TFindProc);
var i: Integer;
begin
for i:=0 to ControlCount-1 do
if Controls[i] is T then
AProc(Controls[i] as T);
end;
For example if you have a Form or Control and you want to do something only with its TButton children controls:
uses MyFilter;
// FireMonkey:
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
TEnumerableFilter
begin
Sender.Visible:=CheckBox1.IsChecked;
end);
end;
// VCL:
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
Find
begin
Sender.Visible:=CheckBox1.Checked;
end);
end;
(The VCL version is a proper "class helper", as its not possible to create class helpers for generic types).
The code for FireMonkey:
uses
System.Generics.Collections;
type
TFindProc
TEnumerableFilter
public
procedure Find(const AProc:TFindProc
end;
procedure TEnumerableFilter
var Item : T;
begin
for Item in Self do
if Item is T then
AProc(Item as T);
end;
The code for VCL:
uses VCL.Controls;
type
TFindProc
TVCLEnumerableFilter=class helper for TWinControl
public
procedure Find
end;
procedure TVCLEnumerableFilter.Find
var i: Integer;
begin
for i:=0 to ControlCount-1 do
if Controls[i] is T then
AProc(Controls[i] as T);
end;
Comments
Post a Comment