procedure DoSomething(A: array of const);
declares a procedure called
DoSomething
that can operate on heterogeneous arrays.
The
array of const
construction
is equivalent to
array of
TVarRec
.
TVarRec
, declared in the
System
unit,
represents a record with a variant part that can hold values of integer, Boolean, character, real, string, pointer, class,
class reference, interface, and variant types.
TVarRec
's
VType
field indicates the type of each element in the array.
Some types are passed
as pointers rather than values; in particular, long strings are
passed as Pointer and must
be typecast to string.
The following example uses a variant open array parameter in a function that creates a string representation of each
element passed to it and concatenates the results into a single string. The string-handling routines called in this
function
are defined in
SysUtils
.
function MakeStr(const Args: array of const): string
var
I: Integer;
begin
Result := '';
for I := 0 to High(Args) do
with Args[I] do
case VType of
vtInteger: Result := Result + IntToStr(VInteger);
vtBoolean: Result := Result + BoolToStr(VBoolean);
vtChar: Result := Result + VChar;
vtExtended: Result := Result + FloatToStr(VExtended^);
vtString: Result := Result + VString^;
vtPChar: Result := Result + VPChar;
vtObject: Result := Result + VObject.ClassName;
vtClass: Result := Result + VClass.ClassName;
vtAnsiString: Result := Result + string(VAnsiString);
vtCurrency: Result := Result + CurrToStr(VCurrency^);
vtVariant: Result := Result + string(VVariant^);
vtInt64: Result := Result + IntToStr(VInt64^);
end;
end;
We can call this function using an open array constructor. For example,
MakeStr(['test', 100, ' ', True, 3.14159, TForm])
returns
the string
'test100 T3.14159TForm'
.
Dostları ilə paylaş: