delphi prototype pattern

前端 未结 5 532
梦毁少年i
梦毁少年i 2021-01-03 05:30

I was wondering, is there anything in the RTTI of Delphi that will do the same as MemberwiseClone does in C# for the simple implementation of the prototype pattern. I saw so

5条回答
  •  攒了一身酷
    2021-01-03 06:10

    There’s a way to perform a deep-copy (clone) of an object in Delphi. It works for the latest versions of Delphi (2010 and above). See the code snipped below...it’s actually quite simple and you don't need external libraries. You can find more information here: http://www.yanniel.info/2012/02/deep-copy-clone-object-delphi.html

    function DeepCopy(aValue: TObject): TObject;
    var
      MarshalObj: TJSONMarshal;
      UnMarshalObj: TJSONUnMarshal;
      JSONValue: TJSONValue;
    begin
      Result:= nil;
      MarshalObj := TJSONMarshal.Create;
      UnMarshalObj := TJSONUnMarshal.Create;
      try
        JSONValue := MarshalObj.Marshal(aValue);
        try
          if Assigned(JSONValue) then
            Result:= UnMarshalObj.Unmarshal(JSONValue);
        finally
          JSONValue.Free;
        end;
      finally
        MarshalObj.Free;
        UnMarshalObj.Free;
      end;
    end;
    

提交回复
热议问题