TClass Type
TClass
is the root metaclass type. You can use
TClass
any time you need a generic class
reference.
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
.
// 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