var
button : TButton;
begin
button := TButton.Create(nil);
....
try
...
finally
button.Free;
end;
end;
button : TButton;
begin
button := TButton.Create(nil);
....
try
...
finally
button.Free;
end;
end;
调试欢乐多
记住一定要写在try...finally...end结构中,才能保证一定能够释放。
button : TButton;
begin
button := TButton.Create(Self); //Self.Free就会触发buttoon.Free
....
end;
btn : TButton;
begin
btn := TButton.Create(handle);
try
...
finally
btn.Free;
end;
end;
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
FButton: TButton;
public
{ Public declarations }
end;var
Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
begin //创建
if not Assigned(FButton) then
FButton := TButton.Create(Self);
FButton.Parent := Self;
FButton.Caption := '圣诞快乐';
end;procedure TForm1.Button2Click(Sender: TObject);
begin //释放
if Assigned(FButton) then
FButton.Free;
end;end.