10

我有一个复杂的对象进行深度复制(大量的数组、对象、指针、继承层、数百个不同类型的成员等等),并且通过 Delphi 的 Assign 方法重新创建它并不高效,而且很可能太复杂了.

我一直在看,Rtti这似乎是一个不错的选择,但到目前为止,我无法涵盖所有​​可能的情况。我不想浪费这么多时间,希望能找到一个好的简单的例子。不幸的是,我还没有找到一个。到目前为止,我一直在做的是,TRttiField使用循环 ( TRttiType.GetFields()) 遍历对象中的所有内容,并尝试使用基于TTypeKind值的指针来分配所有内容。(tkPointer, tkClass, tkClassRef...)

我找到了一个 JSON/Marshalling 示例,但它无法深度复制我的复杂对象;我有错误;

内部:当前不支持类型 tkPointer

http://www.yanniel.info/2012/02/deep-copy-clone-object-delphi.html

Delphi 中是否有任何接近 C# 二进制序列化和使用内存流创建深层副本的东西。或者您知道在 Delphi 中是否有一个很好且简单的示例,使用 RTTI 或 JSON/Marshalling 进行深度复制,可以处理最复杂的对象?

4

2 回答 2

7

简而言之,您不能使用 rtti 来简化深层复制(这将比使用经典分配覆盖更复杂且容易出错)

所以你需要更接近TPersistent及其子对象并正确覆盖AssignAssignTo方法(没有更简单的方法)

于 2013-06-04T19:32:58.613 回答
1

亚历克斯我和你有同样的问题,我有点头疼,写了下面的代码来回答我的问题,希望也能遇到你或其他人。

function TModel.Clone(pObj:TObject): TObject;
procedure WriteInField(pField:TRttiField; result, source:Pointer);
var
  Field:TRttiField;
  Val:TValue;
  Len: NativeInt;
  I :Integer;
  tp:TRttiType;
  ctx:TRttiContext;
begin
   if not pField.GetValue(source).IsEmpty then
     case pField.FieldType.TypeKind of
        TTypeKind.tkRecord:  
        begin
          for Field in pField.FieldType.GetFields do
             WriteInField(Field, PByte(result)+pField.Offset, pField.GetValue(source).GetReferenceToRawData);
        end;
        TTypeKind.tkClass:   
        begin
          Val:=Self.Clone(pField.GetValue(source).AsObject);
          if Assigned(TObject(pField.GetValue(result).AsObject)) then
            pField.GetValue(result).AsObject.Free;

          pField.SetValue(result,Val);
        end;
        TTypeKind.tkDynArray:
        begin
          Len := pField.GetValue(source).GetArrayLength;
          for I := 0 to Len -1 do
            case pField.GetValue(source).GetArrayElement(I).Kind of
              TTypeKind.tkRecord:
              begin
                tp:=ctx.GetType(pField.GetValue(source).GetArrayElement(I).TypeInfo);
                for Field in tp.GetFields do
                  WriteInField(Field,PByte(result)+Field.Offset, pField.GetValue(source).GetReferenceToRawData);

              end;
              TTypeKind.tkClass:
              begin
                Val:=Self.Clone(pField.GetValue(source).GetArrayElement(I).AsObject);
                DynArraySetLength(PPointer(PByte(result)+pField.Offset)^,pField.GetValue(source).TypeInfo,1,@Len);
                pField.GetValue(result).SetArrayElement(I,Val);
              end;
            else
              DynArraySetLength(PPointer(PByte(result)+pField.Offset)^,pField.GetValue(source).TypeInfo,1,@Len);
              pField.GetValue(result).SetArrayElement(I, pField.GetValue(source).GetArrayElement(I));
            end;

        end;
     else
        pField.SetValue(result,pField.GetValue(source));
     end;
end;
var
  Context: TRttiContext;
  IsComponent, LookOutForNameProp: Boolean;
  RttiType: TRttiType;
  Method: TRttiMethod;
  MinVisibility: TMemberVisibility;
  Params: TArray<TRttiParameter>;
  PropFild: TRttiField;
  Fild: TRttiField;
  SourceAsPointer, ResultAsPointer: Pointer;
  ObjWithData:TObject;
  Value:TValue;

begin
try
  if Assigned(pObj) then
    ObjWithData := pObj
  else
    ObjWithData := Self;
  RttiType := Context.GetType(ObjWithData.ClassType);
  //find a suitable constructor, though treat components specially
  IsComponent := (ObjWithData is TComponent);
  for Method in RttiType.GetMethods do
    if Method.IsConstructor then
    begin
      Params := Method.GetParameters;
      if Params = nil then Break;
      if (Length(Params) = 1) and IsComponent and
         (Params[0].ParamType is TRttiInstanceType) and
         SameText(Method.Name, 'Create') then Break;
    end;
  if Params = nil then
    Result := Method.Invoke(ObjWithData.ClassType, []).AsObject
  else
    Raise Exception.CreateFmt('Object Invalid to clone : ''%s''', [ObjWithData.ClassName]);
  try

    //loop through the props, copying values across for ones that are read/write
    Move(ObjWithData, SourceAsPointer, SizeOf(Pointer));
    Move(Result, ResultAsPointer, SizeOf(Pointer));
    for PropFild in RttiType.GetFields do
      WriteInField(PropFild,ResultAsPointer,SourceAsPointer);

  except
    Result.Free;
    raise;
  end;
finally
  ObjWithData := nil;
end;

end;
于 2015-11-27T19:46:54.500 回答