如何获取const数组的类型和值?

时间:2023-01-14 14:37:25

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.

在我的Delphi开发中,我想将一个“const数组”(也可以包含类)传递给一个过程,并在过程循环中传递元素并检测元素类型如下所示。

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?

如何循环发送的数组元素并检测它的类型?

2 个解决方案

#1


7  

for I := Low(Args) to High(Args) do
  case TVarRec(Args[I]).VType of
    vtInteger:
      ...
  end;

#2


17  

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

假设您使用的是Unicode Delphi(否则,您必须更改字符串大小写):

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;

#1


7  

for I := Low(Args) to High(Args) do
  case TVarRec(Args[I]).VType of
    vtInteger:
      ...
  end;

#2


17  

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

假设您使用的是Unicode Delphi(否则,您必须更改字符串大小写):

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;