我可以使用assign来复制对象的对象吗?

san*_*206 2 delphi clone

我有一个从TPersistent继承3度的对象,我想使用Assign过程克隆它.

MyFirstObj := GrandSonOfPersistent.Create();
//I modify the objects inside MyFirstObj
MySecondObj := GrandSonOfPersistent.Create();
MySecondObj.Assign(MyFirstObject);
Run Code Online (Sandbox Code Playgroud)

我该怎么检查它有效?当对象有许多其他对象时它是否有效?

我正在尝试克隆一个对象,这是正确的方法吗?

J..*_*... 7

Assign是一种虚拟方法.任何继承的后代类都TPersistent应该重写,Assign以处理在基类之上添加的任何新成员的深度复制.如果您的类没有覆盖Assign来处理这些深层副本,那么使用Assign这样的副本将不会成功.尝试使用源对象的实现来执行复制的Assign调用的基本实现AssignTo.如果源和目标对象都不能处理副本,则会引发异常.

请参阅:文档

例如:

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. 
Run Code Online (Sandbox Code Playgroud)

请注意,继承自的任何类TPersistent只应inherited在无法处理Assign调用时调用.但是,后代类应始终调用inherited,因为父级也可以执行操作,如果没有,将处理调用base的传递inherited:

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;
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我已经显示了字符串.对于对象成员,您需要使用他们的Assign方法或以其他方式执行复制.

  • 在重写`Assign()`中,在传递未知源对象时,不应为字段分配默认值.这不是标准做法.如果`Assign()`不识别对象,`TPersistent`将对象传递给`AssignTo()`.如果`AssignTo()`无法识别该对象,则会引发异常,并且根本没有修改分配给的原始对象.这是预期的行为. (2认同)