Delphi Rtti:如何从TObjectList <t> </t>获取对象

时间:2012-09-19 15:24:15

标签: delphi generics delphi-xe rtti tobjectlist

我正在为xml转换器开发一个自定义类,其中一个要求是能够传输TObjectList<T>个字段。
我试图调用ToArray()方法来获取TObjectlist的对象,但我得到'无效类类型转换',因为类型显然不匹配。

以此课程为例:

type
  TSite = class
    Name : String;
    Address : String; 
  end;

  TSites = class
    Sites : TObjecList<TSite>;
  end;  

我只需要从站点TObjectList获取站点对象。 请记住我正在使用RTTI,因此我不知道TObjectList中的ObjectType,因此Typecasting将无效。这就是我所拥有的,但它似乎是一个死胡同(Obj在这里是TobjectList<TSite>):

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方法

修改

感谢David,我有我的解决方案:

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;

我愿意接受建议,也许有更多'聪明'的方法来实现这个目标......

1 个答案:

答案 0 :(得分:4)

您的代码失败,因为动态数组不是TObject。

你可以这样做:

Value := Meth.Invoke(Obj, []);
Assert(Value.IsArray);
SetLength(Arr, Value.GetArrayLength);
for i := 0 to Length(Arr)-1 do
  Arr[i] := Value.GetArrayElement(i).AsObject;
相关问题