写了一个测试代码, 创建一个窗体拉上一个按钮控件,复制以下的代码
- unit Unit1;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
- type
- TForm1 = class(TForm)
- Button1: TButton;
- procedure Button1Click(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- end;
- C1 = class //(TPersistent)
- private
- p1:string;
- public
- procedure Show;
- procedure AfterConstruction; override;
- procedure BeforeDestruction; override;
- constructor Create; virtual;
- procedure test(str: string);
- end;
- C2 = class(C1)
- public
- constructor Create; override;
- constructor CreateNew; virtual;
- procedure AfterConstruction; override;
- procedure Show;
- end;
- C3 = class(c2)
- end;
- var
- Form1: TForm1;
- implementation
- {$R *.dfm}
- { C1 }
- procedure C1.AfterConstruction;
- begin
- inherited AfterConstruction;
- test('C1.AfterConstruction'); ;
- end;
- procedure C1.BeforeDestruction;
- begin
- test('C1.BeforeDestruction'); ;
- inherited BeforeDestruction;
- end;
- constructor C1.Create;
- begin
- inherited;
- test('C1.Create');
- end;
- procedure C1.Show;
- begin
- ShowMessage(p1);
- end;
- procedure C1.test(str: string);
- begin
- ShowMessage(str);
- end;
- { C2 }
- procedure C2.AfterConstruction;
- begin
- inherited;
- ShowMessage('C2.AfterConstruction');
- end;
- constructor C2.Create;
- begin
- inherited Create;
- test('c2.Create'); ;
- end;
- constructor C2.CreateNew;
- begin
- Create;
- test('c2.CreateNew');
- end;
- procedure C2.Show;
- begin
- inherited Show;
- test('c2.show');
- end;
- procedure TForm1.Button1Click(Sender: TObject);
- var
- a: c3;
- b: c2;
- c:c1;
- begin
- c:=c3.CreateNew;
- c.p1:='aaa';
- c.Show;
- c.test('aaaaa');
- end;
- end.
单击按钮时,依次显示:
C1.Create // 运行了c:=c3.CreateNew; inherited Create;
C2.Create //Create;
C2.CreateNew
C1.AfterConstruction C2.AfterConstruction 里的inherited
C2.AfterConstruction
aaa
aaaaa
在对象创建前会自动调用AfterConstruction,资料参考空间里之前发布的文章