Skip to content

Instantly share code, notes, and snippets.

@dipold
Created May 19, 2016 14:48
Show Gist options
  • Save dipold/99e47c218f3986fd5c2e71bc4fadecd8 to your computer and use it in GitHub Desktop.
Save dipold/99e47c218f3986fd5c2e71bc4fadecd8 to your computer and use it in GitHub Desktop.
How to make TComparer work
procedure TForm1.Button1Click(Sender: TObject);
var
ArrayProcs: TArray<TProc>;
Proc: TProc;
Comparer : IComparer<TProc>;
ProcA: TProc;
ProcB: TProc;
ProcC: TProc;
Index: Integer;
begin
ProcA := procedure begin showmessage('A') end;
ProcB := procedure begin showmessage('B') end;
ProcC := procedure begin showmessage('C') end;
SetLength(ArrayProcs, 3);
ArrayProcs[0] := ProcA;
ArrayProcs[1] := ProcB;
ArrayProcs[2] := ProcC;
for Proc in ArrayProcs do
Proc(); //show A B C
Comparer := TComparer<TProc>.Construct(
function(const Left, Right: TProc): Integer
begin
Result := TComparer<Integer>.Default.Compare(Integer(@Left), Integer(@Right));
end);
if (TArray.BinarySearch<TProc>(ArrayProcs, ProcB, Index, Comparer)) then
//Code to remove ProcB from ArrayProcs but this line never execute
for Proc in ArrayProcs do
Proc(); //should show A C
end;
@sglienke
Copy link

var
  Procs: TList<TProc>;
  Proc: TProc;

  ProcA: TProc;
  ProcB: TProc;
  ProcC: TProc;
begin
  ProcA := procedure begin Writeln('A') end;
  ProcB := procedure begin Writeln('B') end;
  ProcC := procedure begin Writeln('C') end;

  Procs := TList<TProc>.Create;
  Procs.Add(ProcA);
  Procs.Add(ProcB);
  Procs.Add(ProcC);

  for Proc in Procs do
    Proc(); //show A B C

  Procs.Remove(ProcB);

  for Proc in Procs do
    Proc(); //should show A C

  Readln;
end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment