Name

TClass Type

Syntax

type TClass = class of TObject;

Description

TClass is the root metaclass type. You can use TClass any time you need a generic class reference.

Tips and Tricks

  • You can call any class method by invoking the method from a class reference.

  • You cannot use the is and as operators on a class reference, but you can call the InheritsFrom class method to test whether a class reference inherits from another class.

  • Delphi represents a class reference as a pointer to the class’s VMT. Thus, the size of a TClass reference is the same size as a Pointer.

Example

// Map class names to class references.
type
  TClassMap = class
  private
    fList: TStrings;
    function GetClass(const Name: string): TClass;
    procedure PutClass(const Name: string; Value: TClass);
  public
    procedure Add(ClsRef: TClass);
    property Classes[const Name: string]: TClass
        read GetClass write SetClass; default;
  end;

procedure TClassMap.Add(ClsRef: TClass);
begin
  // TStrings takes TObject as the associated data,
  // so cast TClass to TObject.
  fList.AddObject(ClsRef.ClassName, TObject(ClsRef));
end;

function TClassMap.GetClass(const Name: string): TClass;
begin
  Result := TClass(fList.Objects[fList.IndexOf(Name)]);
end;

procedure TClassMap.SetClass(const Name: string; Value: TClass);
var
  Index: Integer;
begin
  Index := fList.IndexOf(Name);
  if Index < 0 then
    fList.AddObject(Name, TObject(Value))
  else
    fList.Objects[Index] := TObject(Value);
end;
...
var
  Map: TClassMap;
  Cls: TClass;
...
Map.Add(TObject);
Map.Add(TComponent);
Map.Add(TForm);
Cls := Map['TButton'].ClassParent; // Cls := TButtonControl

See Also

Class Keyword, Of Keyword, Self Variable, TObject Type, Type Keyword
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset