S
S
smigles2018-08-20 21:46:04
Delphi
smigles, 2018-08-20 21:46:04

How to merge procedures with the same code in Delphi?

There are two procedures in Delphi:

procedure procInt(var arr: array of integer);
var
  p: integer;

begin
  ...
end;

procedure procStr(var arr: array of string);
var
  p: string;

begin
  ...
end;

Procedures have exactly the same code inside the begin ... end;. They differ only in the data type of the array parameter arrand the declared variable p.
Is it possible to somehow combine these two procedures so as not to write the same code?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
kalapanga, 2018-08-20
@kalapanga

For example like this:

type
  TArrayHelper<T> = class
    class procedure CoolProc(var arr: TArray<T>); // Ваша процедура
  end;

…

implementation

class procedure TArrayHelper<T>.CoolProc(var arr: TArray<T>); // Реализация Вашей процедуры
var
  Tmp: T;
begin
    Tmp := arr[0];
    arr[0] := arr[4];
    arr[4] := Tmp;
end;

procedure TForm1.Button1Click(Sender: TObject); // Проверка работы
var
  i: integer;
  iarr: TArray<Integer>;
  sarr: TArray<String>;
begin
  iarr := TArray<Integer>.Create(1, 2, 3, 4, 5);
  sarr := TArray<String>.Create('one', 'two', 'three', 'four', 'five');
  TArrayHelper<Integer>.CoolProc(iarr); // Вызов для целых чисел
  TArrayHelper<String>.CoolProc(sarr); // Вызов для строк
  for I := 0 to 4 do
  begin
    memo1.Lines.Add(IntToStr(iarr[i]));
    memo2.Lines.Add(sarr[i]);
  end;
end;

A
Andrey Skorzhinsky, 2018-08-21
@AndyKorg

procedure procIntOrStr(var arr: array of integer); overload;
procedure procIntOrStr(var arr: array of string); overload;

X
xDimus, 2018-08-21
@xDimus

Alternatively, you can leave one procedure, for example str, and before calling, convert the int array to the str array.
What does it do for you

exactly the same code inside the block
?

M
microfrog, 2018-09-07
@microfrog

procedure procVar(var arr: array of Variant);
Inside, determine the specific type of variables in the array and perform the necessary actions on them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question