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.

posted on 2008-01-11 16:43  万一  阅读(4298)  评论(1编辑  收藏  举报