Let's assume that you need to access some of the protected properties
(or methods) in a component's instance. Of course, you could create a
new class that extends the original class, make the protected members
public, and instantiate the new class instead.
However, in some situations, this could be either too complicated or
just not possible. For instance, if you need access to a protected
property for only one or two operations in a standard component,
creating a new component, registering it, and then managing it could be
just too cumbersome (I never got to like Delphi's component management).
Or maybe the class is instantiated outside of your
code and you have no way of changing that code?
The code below is a bit of a hack (or rather a shortcut), but in
situations like those mentioned above works quite nicely. Let's take, for
instance, TPanel and its protected property Canvas.
You can expose this member as follows:
type
TCanvasPanel = class(TPanel)
public
property Canvas;
end;
...
// Now let's say that Panel is instantiated outside of your code,
// but you still need access to its Canvas:
TCanvasPanel(Panel).Canvas.Ellipse(10, 10, 50, 50);
...
// However the following instruction will not work -
// a runtime error will be reported (EInvalidCast):
(Panel as TCanvasPanel).Canvas.Ellipse(10, 10, 50, 50);
...
That's Delphi, but you should be able to do this in other languages
that allow type casts without too strict type checking.
Top
|