Can I use assignment to duplicate object objects?

I have an object that inherits 3rd degree from TPersistent, and I want to clone it using the Assign procedure.

MyFirstObj := GrandSonOfPersistent.Create(); //I modify the objects inside MyFirstObj MySecondObj := GrandSonOfPersistent.Create(); MySecondObj.Assign(MyFirstObject); 

How can I check the work? Does it work when objects have many other objects?

I'm trying to clone an object, is this the right way to do this?

+2
source share
1 answer

Assign is a virtual method. Any descendant classes that inherit from TPersistent must override Assign to handle deep copying of any new members added on top of the base class. If your classes do not override Assign to handle these deep copies, then using Assign cannot make such a copy. The base Assign implementation calls AssignTo , which attempts to use the implementation of the source object to execute the copy. If neither the source nor the target can handle the copy, an exception is thrown.

See: Documentation

Example:

 unit SomeUnit; interface uses Classes; type TMyPersistent = class(TPersistent) private FField: string; public property Field: string read FField write FField; procedure Assign (APersistent: TPersistent) ; override; end; implementation procedure TMyPersistent.Assign(APersistent: TPersistent) ; begin if APersistent is TMyPersistent then Field := TMyPersistent(APersistent).Field else inherited Assign (APersistent); end; end. 

Note that any class that inherits from TPersistent should only call inherited if it cannot handle the Assign call. However, the class of descendants should always be inherited, since the parent can also perform actions for execution, and if not, it processes the transfer that calls the inherited base:

 type TMyOtherPersistent = class(TMyPersistent) private FField2: string; public property Field2: string read FField2 write FField2; procedure Assign (APersistent: TPersistent) ; override; end; implementation procedure TMyPersistent.Assign(APersistent: TPersistent) ; begin if APersistent is TMyOtherPersistent then Field2 := TMyOtherPersistent(APersistent).Field2; inherited Assign (APersistent); end; 

In this example, I showed the lines. For members of an object, you need to either use their Assign methods or execute a copy in another way.

+6
source

Source: https://habr.com/ru/post/970189/


All Articles