Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the types and values of an array of const?

Tags:

arrays

delphi

In my Delphi development, I want to pass an "array of const"(that can contains class too) to a procedure, and in procedure loop on elements and detect type of element as bellow.

Procedure Test(const Args : array of const);
begin
end;

and in my code call it with some variables

Procedure Test();
begin
  cls := TMyObject.create;
  i := 123;
  j := 'book';
  l := False;
  Test([i,j,l, cls, 37.8])
end;

How loop on sent array elements and detect it's type?

like image 985
Moh Tarvirdi Avatar asked Mar 28 '12 15:03

Moh Tarvirdi


2 Answers

Assuming you are using Unicode Delphi (otherwise, you have to alter the string case):

procedure test(const args: array of const);
var
  i: Integer;
begin
  for i := low(args) to high(args) do
    case args[i].VType of
      vtInteger: ShowMessage(IntToStr(args[i].VInteger));
      vtUnicodeString: ShowMessage(string(args[i].VUnicodeString));
      vtBoolean: ShowMessage(BoolToStr(args[i].VBoolean, true));
      vtExtended: ShowMessage(FloatToStr(args[i].VExtended^));
      vtObject: ShowMessage(TForm(args[i].VObject).Caption);
      // and so on
    end;
end;


procedure TForm4.FormCreate(Sender: TObject);
begin
  test(['alpha', 5, true, Pi, Self]);
end;
like image 133
Andreas Rejbrand Avatar answered Oct 14 '22 08:10

Andreas Rejbrand


for I := Low(Args) to High(Args) do
  case TVarRec(Args[I]).VType of
    vtInteger:
      ...
  end;
like image 22
Ondrej Kelle Avatar answered Oct 14 '22 08:10

Ondrej Kelle