[fpc-pascal] Assign() vs AssignTo()
stdreamer
stdreamer at freemail.gr
Sun Feb 14 03:51:25 CET 2016
On 11/02/2016 17:13 μμ, Graeme Geldenhuys wrote:
> Hi,
>
> In TPersistent, we have two virtual methods. Assign() which calls
> AssignTo().
>
> 1) Why are they both virtual? It seems like Assign() is what I call a
> template method, farming its work out to other helper methods - in this
> case, AssignTo(). Normally template methods are not virtual, but their
> helper methods (the ones doing the actual work) are. So again, why is
> Assign() virtual?
Different functionality you need both of them for different reasons see
below.
> 2) Now seeing that both are virtual, and that is probably not going to
> change in the RTL, which method is the preferred method to override so
> you have the ability to do MyObject.Assign(MySource)? I've been
> overriding Assign(), but thinking that maybe I should have overridden
> AssignTo() instead.
As a rule of thumb you always override Assign to make sure that your
control can copy data from any other. You only override AssignTo to
enable 3rd party controls to copy data from your controls.
Lets assume that you right a control TDBGrid based on VirtualstringTree ee
TMyDbGrid = class(TVirtualStringTree)
.
.
.
end;
By overriding the assign method you teach TMyDBGrid how to copy data
from a TDBGrid. Now lets assume that you want to be able to copy data
from your TMyDBGrid to TDBGrid as well you have two choices
1) create a new control
TNewDBGrid = class(TDBGrid)
end;
and override the assign method
2) override the AssignTo method of TMyDBgrid control and there copy the
data to TDBGrid your self with out touching TDBgrid.
This is a simple but powerful feature that allows you to teach other
controls how to copy data from your controls with out the need to change
their code. Something common on well written libraries.
PS. The choice of the example control is not random, I came to
understand the importance of AssignTo when I coded my own dbgrid and
wanted to be able to assign data to multiple other grids including the
DevExpress grids.
More information about the fpc-pascal
mailing list