Delphi Rtti: cómo obtener objetos de TObjectList <T>
Estoy trabajando en una clase personalizada a xml converter y uno de los requisitos es la capacidad de transmitirTObjectList<T>
campos.
Estoy tratando de invocar elToArray()
método para obtener los objetos de la lista de objetos, pero obtengo 'Typecast de clase no válido' porque los tipos obviamente no coinciden.
Toma esta clase por ejemplo:
type
TSite = class
Name : String;
Address : String;
end;
TSites = class
Sites : TObjecList<TSite>;
end;
Solo necesito obtener los objetos del sitio de la lista de tareas de los sitios. Por favor, tenga en cuenta que estoy usando RTTI, por lo que no sé el ObjectType en TObjectList,así que Typecasting no funcionará. Esto es lo que tengo pero parece un callejón sin salida (Obj esTobjectList<TSite>
aquí):
function TXmlPersister.ObjectListToXml(Obj : TObject; Indent: String): String;
var
TypInfo: TRttiType;
meth: TRttiMethod;
Arr : TArray<TObject>;
begin
Result := '';
TypInfo := ctx.GetType(Obj.ClassInfo);
Meth := TypInfo.GetMethod('ToArray');
if Assigned(Meth) then
begin
Arr := Invoke(Obj, []).AsType<TArray<TObject>>; // invalid class typecast error
if Length(Arr) > 0 then
begin
// get objects from array and stream them
...
end;
end;
Cualquier forma de sacar los objetos de TObjectList a través de RTTI es buena para mí. Por alguna extraña razón, no veo los métodos GetItem / SetItem en TypInfo
EDITAR
Gracias a David tengo mi solución:
function TXmlPersister.ObjectListToXml(Obj : TObject; Indent: String): String;
var
TypInfo: TRttiType;
meth: TRttiMethod;
Value: TValue;
Count : Integer;
begin
Result := '';
TypInfo := ctx.GetType(Obj.ClassInfo);
Meth := TypInfo.GetMethod('ToArray');
if Assigned(Meth) then
begin
Value := Meth.Invoke(Obj, []);
Assert(Value.IsArray);
Count := Value.GetArrayLength;
while Count > 0 do
begin
Dec(Count);
Result := Result + ObjectToXml(Value.GetArrayElement(Count).AsObject, Indent);
end;
end;
end;
Estoy abierto a sugerencias, tal vez haya más formas 'inteligentes' para lograr este objetivo ...