我正在开发一个自定义类到 xml 转换器,要求之一是能够进行流式传输TObjectList<T>
fields.
我正在尝试调用ToArray()
方法来获取 TObjectlist 的对象,但我得到“无效的类类型转换”,因为类型显然不匹配。
以这个类为例:
type
TSite = class
Name : String;
Address : String;
end;
TSites = class
Sites : TObjecList<TSite>;
end;
我只需要从站点 TObjectList 获取站点对象。
请记住,我正在使用 RTTI,所以我不知道 TObjectList 中的 ObjectType,所以类型转换不起作用。这就是我所拥有的,但它似乎是一个死胡同(Obj 是TobjectList<TSite>
here):
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;
任何通过 RTTI 从 TObjectList 中获取对象的方法对我来说都是有好处的。
由于某些奇怪的原因,我在 TypInfo 中没有看到 GetItem/SetItem 方法
EDIT
感谢大卫,我有了我的解决方案:
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;
我愿意接受建议,也许有更多“聪明”的方法来实现这个目标......