Delphi Rtti: como obter objetos de TObjectList <T>
Eu estou trabalhando uma classe personalizada para conversor xml e um dos requisitos é a capacidade de transmitirTObjectList<T>
Campos.
Eu estou tentando invocar oToArray()
método para se apossar dos objetos da TObjectlist, mas eu recebo 'typecast de classe inválida' porque os tipos obviamente não correspondem.
pegue esta classe por exemplo:
type
TSite = class
Name : String;
Address : String;
end;
TSites = class
Sites : TObjecList<TSite>;
end;
Eu só preciso obter os objetos do site do Sites TObjectList. Por favor, tenha em mente que eu estou usando o RTTI, então eu não sei o ObjectType em TObjectList,então o Typecasting não funciona. Isto é o que eu tenho, mas parece um beco sem saída (Obj éTobjectList<TSite>
Aqui):
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;
Qualquer maneira de obter os objetos fora do TObjectList via RTTI é bom para mim. Por algum motivo estranho eu não vejo os métodos GetItem / SetItem em TypInfo
EDITAR
Graças a David eu tenho a minha solução:
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;
Estou aberto a sugestões, talvez existam formas mais "inteligentes" para alcançar este objetivo ...