unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(Self.ClassName); {TForm1 - Form1 的類名}
ShowMessage(Self.ClassParent.ClassName); {TForm - Form1 的父類名}
ShowMessage(Self.ClassParent.ClassParent.ClassName); {TCustomForm - Form1 的爺爺類名}
end;
//
procedure TForm1.Button2Click(Sender: TObject);
var
MyClass: TClass;
{TClass 是 TObject 的類引用; 它和 TObject 有著相同的功能, 但總之不是一個類型}
begin
{對象的 ClassType 方法返回對象的 TClass}
ShowMessage(Self.ClassType.ClassName); {TForm1 - Form1 的類名}
MyClass := Self.ClassType;
ShowMessage(MyClass.ClassName); {TForm1 - Form1 的類名}
end;
//
procedure TForm1.Button3Click(Sender: TObject);
var
MyClass: TClass;
begin
{對象的 ClassParent 方法返回的也是 TClass, 可以把對象的 ClassParent 賦予 TClass 變量}
MyClass := Self.ClassType;
ShowMessage(MyClass.ClassName); {TForm1 - Form1 的類名}
MyClass := MyClass.ClassParent;
ShowMessage(MyClass.ClassName); {TForm - Form1 的父類名}
MyClass := MyClass.ClassParent;
ShowMessage(MyClass.ClassName); {TCustomForm - Form1 的爺爺類名}
end;
//遍歷窗體的所有父類
procedure TForm1.Button4Click(Sender: TObject);
var
MyClass: TClass;
begin
MyClass := Self.ClassType;
while MyClass <> nil do
begin
ShowMessage(MyClass.ClassName);
MyClass := MyClass.ClassParent;
end;
{將依次顯示:
TForm1
TForm
TCustomForm
TScrollingWinControl
TWinControl
TControl
TComponent
TPersistent
TObject
}
end;
end.