Generic Anonymous Methods
Radek Červinka - 17/May/2020
Radek Červinka - 17/May/2020
[SHOWTOGROUPS=4,20]
In newer Delphi, at least XE3 - I haven't looked deeper, a few generic and anonymous methods are defined in the System.SysUtils unit .
What is this for? One of the uses is a repetitive function that differs in only one part, so we just pass that one part as an anonymous method (in the Browse example, which has a generic function with two parameters as the second parameter).
And while I'm at it, further use of anonymous methods is needed in the development for FMX, where a lot of asynchronous dialogs use the same approach, e.g.
TInputCloseDialogProc = reference to procedure(const AResult: TModalResult);
[/SHOWTOGROUPS]
In newer Delphi, at least XE3 - I haven't looked deeper, a few generic and anonymous methods are defined in the System.SysUtils unit .
Код:
// Generic Anonymous method declarations
type
TProc = reference to procedure;
TProc<T> = reference to procedure (Arg1: T);
TProc<T1,T2> = reference to procedure (Arg1: T1; Arg2: T2);
TProc<T1,T2,T3> = reference to procedure (Arg1: T1; Arg2: T2; Arg3: T3);
TProc<T1,T2,T3,T4> = reference to procedure (Arg1: T1; Arg2: T2; Arg3: T3; Arg4: T4);
TFunc<TResult> = reference to function: TResult;
TFunc<T,TResult> = reference to function (Arg1: T): TResult;
TFunc<T1,T2,TResult> = reference to function (Arg1: T1; Arg2: T2): TResult;
TFunc<T1,T2,T3,TResult> = reference to function (Arg1: T1; Arg2: T2; Arg3: T3): TResult;
TFunc<T1,T2,T3,T4,TResult> = reference to function (Arg1: T1; Arg2: T2; Arg3: T3; Arg4: T4): TResult;
TPredicate<T> = reference to function (Arg1: T): Boolean;
What is this for? One of the uses is a repetitive function that differs in only one part, so we just pass that one part as an anonymous method (in the Browse example, which has a generic function with two parameters as the second parameter).
Код:
procedure TForm1.Browse(q: TDataset; pLine: TProc<Integer, TField>);
var
x : Integer;
oField: TField;
begin
x := 1;
oField := q.FieldByName('Name');
while not q.Eof do
begin
pLine(x, oField);
q.Next;
inc(x);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Browse(FDQuery1,
procedure(Line: Integer; Field: TField)
begin
memo1.Lines.Add(Format('%d: %s', [Line, Field.AsString]));
end);
Browse(FDQuery2,
procedure(Line: Integer; Field: TField)
begin
log.Lines.Add(Format('%d: %s', [Line, Field.AsString]));
end);
end;
And while I'm at it, further use of anonymous methods is needed in the development for FMX, where a lot of asynchronous dialogs use the same approach, e.g.
TInputCloseDialogProc = reference to procedure(const AResult: TModalResult);
Код:
TDialogService = class
…
class procedure ShowMessage(const AMessage: string; const ACloseDialogProc: TInputCloseDialogProc);
…
[/SHOWTOGROUPS]