我正在尝试使用Delphi XE或更高版本中增强的RTTI功能,将对象读写到XML中。到目前为止,我已经成功地处理了整数、浮点数、字符串、枚举类型、集合和类,但无法正确输出或读取记录。问题似乎在于获取记录属性的实例(指针)。
我猜想如果我能弄清楚如何获取这些值,那么设置它们就不应该是个问题。然后进入数组,哦,天哪!
更新:请参见下面。(已迁移为单独的答案以提高可见性)。
//Outputs Properties To XML
procedure TMyBase.SaveToXML(node: TJclSimpleXMLElem);
var
child , subchild : TjclSimpleXMLElem ;
FContext : TRttiContext ;
FType : TRttiType ;
FProp : TRttiProperty ;
Value : TValue ;
MyObj : TMyBase ;
FField : TRttiField ;
FRecord : TRttiRecordType ;
Data : TValue ;
begin
FContext := TRttiContext.Create ;
FType := FContext.GetType ( self.ClassType ) ;
Child := node.Items.Add ( ClassName ) ;
for FProp in FType.GetProperties do begin
if FProp.IsWritable then begin
case FProp.PropertyType.TypeKind of
tkClass : begin
MyObj := TMyBase ( FProp.GetValue ( self ).AsObject ) ;
MyObj.SaveClass ( Child.Items.Add ( FProp.Name ) , FContext ) ;
end ;
tkRecord : begin
subchild := Child.Items.Add ( FProp.Name ) ;
FRecord := FContext.GetType(FProp.GetValue(self).TypeInfo).AsRecord ;
for FField in FRecord.GetFields do begin
>>> self is not the correct instance <<<
Value := FField.GetValue ( self ) ;
subchild.Items.Add ( FField.Name ).Value := Value.ToString ;
end;
end ;
else begin
Value := FProp.GetValue(self) ;
Child.Items.Add ( FProp.Name ).Value := Value.ToString ;
end;
end;
end ;
end ;
FContext.Free ;
end;
我猜想如果我能弄清楚如何获取这些值,那么设置它们就不应该是个问题。然后进入数组,哦,天哪!
更新:请参见下面。(已迁移为单独的答案以提高可见性)。