Author: Ernesto De Spirito
Is there a way to add new methods and properties to a component without having its
soruce code and having to install a descendant component?
Answer:
Adding new methods and properties
Sometimes we need to add new methods and properties to an existing component (or
change the visibility of existing properties). One way of doing this is modifiying
the component, but this implies having to recompile its package and we would have
to redistribute our changes if we wanted our application to be compiled by others,
and that would
be a bother for the recipients. Sometimes we may not even have that choice because
we may not have the source code. In these situations, better would be to subclass
(derive) the component and add new properties and methods. For example:
1 type2 TEditX = class(TEdit)
3 public4 function GetForeColor: TColor;
5 procedure SetForeColor(color: TColor);
6 property ForeColor: TColor read GetForeColor write SetForeColor;
7 end;
8 9 //These methods could for example be implemented this way: 10 11 function TEditX.GetForeColor: TColor;
12 begin13 Result := Font.Color;
14 end;
15 16 procedure TEditX.SetForeColor(color: TColor);
17 begin18 Font.Color := Color;
19 end;
It's a silly example, of course, but it serves the purpose.
Casting to the new class
We don't need to intall this new component and register it in the components
palette or replace existing controls in our applications (which would be an
unpayable penalty for such small changes and/or additions). Instead, any time we
want to access the new properties and methods, we can just cast the object (for
example Edit1) to our new class. For example:
20 TEditX(Edit1).ForeColor := clRed;
21 22 //or 23 24 TEditX(Edit1).SetForeColor(clRed);
Warning: This casting to a descendant class can only be done if the new class adds
new properties and static methods, but without adding new fields and new virtual or
dynamic methods, although in theory you can override existing virtual methods.
Also, the visibility of existing properties can be changed, as in the InplaceEditor
example
explained in the article "Accessing hidden properties".
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.phphttp://www.latiumsoftware.com/delphi-newsletter.php