Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can get the element type of an array using RTTI

I'm using this code to get the element type of an array

{$APPTYPE CONSOLE}    
uses
  Rtti,
  SysUtils;

type
  TFooArray= array  of TDateTime;

Var
  T : TRttiType;
begin
  try
     T:=TRttiContext.Create.GetType(TypeInfo(TFooArray));
      Writeln(TRttiArrayType(T).ElementType.Name);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

but the application fails with an access violation on this line

Writeln(TRttiArrayType(T).ElementType.Name);

How I can get the element type of an array using the RTTI?

like image 947
Salvador Avatar asked Dec 21 '22 04:12

Salvador


1 Answers

You cast is wrong the TRttiArrayType is for static arrays (and your array is dynamic), to fix the issue use the TRttiDynamicArrayType instead like so :

 Writeln(TRttiDynamicArrayType(T).ElementType.Name);
like image 132
RRUZ Avatar answered Dec 24 '22 01:12

RRUZ