When I try to cast Array of Integer
to TArray<Integer>
in a procedure I get an error E2089 Invalid typecast
. How can I type cast it so that it will work?
program Project11;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Math;
type
TArrayManager<T> = record
class procedure Shuffle(var A: TArray<T>); static;
end;
class procedure TArrayManager<T>.Shuffle(var A: TArray<T>);
var
I, J: Integer;
Temp: T;
begin
for I := High(A) downto 1 do
begin
J := RandomRange(0, I);
Temp := A[I];
A[I] := A[J];
A[J] := Temp;
end;
end;
procedure Test(var A: Array of Integer);
begin
TArrayManager<Integer>.Shuffle(TArray<Integer>(A)); // Invalid typecast????
end;
var
A: Array of Integer;
begin
// TArrayManager<Integer>.Shuffle(TArray<Integer>(A)); // Works
Test(A);
end.
You cannot cast an open array parameter to a dynamic array. They are simply incompatible. If you wish to operate on a slice of the array, without copying, I'm afraid that you will need to pass the array and the indices separately. Like this:
procedure Foo(var A: TArray<Integer>; Index, Count: Integer);
begin
// operate on A[Index] to A[Index+Count-1]
end;