This topic describes the syntax of class helper declarations.
A class helper is a type that - when associated with another class - introduces additional method names and properties which may be used in the context of the associated class (or its descendants). Class helpers are a way to extend a class without using inheritance. A class helper simply introduces a wider scope for the compiler to use when resolving identifiers. When you declare a class helper, you state the helper name, and the name of the class you are going to extend with the helper. You can use the class helper any place where you can legally use the extended class. The compiler's resolution scope then becomes the original class, plus the class helper.
Class helpers provide a way to extend a class, but they should not be viewed as a design tool to be used when developing new code. They should be used solely for their intended purpose, which is language and platform RTL binding.
The syntax for declaring a class helper is:
type identifierName = class helper [(ancestor list)] for classTypeIdentifierName memberList end;
The ancestor list is optional.
A class helper type may not declare instance data, but class fields are allowed.
The visibility scope rules and memberList syntax are identical to that of ordinary class types.
You can define and associate multiple class helpers with a single class type. However, only zero or one class helper applies in any specific location in source code. The class helper defined in the nearest scope will apply. Class helper scope is determined in the normal Delphi fashion (i.e. right to left in the unit's uses clause).
The following code demonstrates the declaration of a class helper:
type TMyClass = class procedure MyProc; function MyFunc: Integer; end; ... procedure TMyClass.MyProc; var X: Integer; begin X := MyFunc; end; function TMyClass.MyFunc: Integer; begin ... end; ... type TMyClassHelper = class helper for TMyClass procedure HelloWorld; function MyFunc: Integer; end; ... procedure TMyClassHelper.HelloWorld; begin writeln(Self.ClassName); // Self refers to TMyClass type, not TMyClassHelper end; function TMyClassHelper.MyFunc: Integer; begin ... end; ... var X: TMyClass; begin X := TMyClass.Create; X.MyProc; // Calls TMyClass.MyProc X.HelloWorld; // Calls TMyClassHelper.HelloWorld X.MyFunc; // Calls TMyClassHelper.MyFunc
Note that the class helper function MyFunc is called, since the class helper takes precedence over the actual class type.
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!