Vis*_*ari 6 delphi delphi-7 delphi-2010 delphi-xe2
我在Delphi中有一个基本的疑问.当我在设计时保留任何组件时,例如TADOConnectuion和按钮点击甚至我写下面的代码然后我没有得到任何错误:
begin
ADOConnection.Free; //No error
ADOConnection.Free; //No error
ADOConnection.Free; //No error
end;
Run Code Online (Sandbox Code Playgroud)
但是如果我在运行时创建相同的对象,则会出现"访问冲突..."错误
begin
ADOConnection := TADOConnection.create(self);
ADOConnection.Free; //No error
ADOConnection.Free; //Getting an "Access Violation..." error
end;
Run Code Online (Sandbox Code Playgroud)
即使我创建如下对象,我也得到相同的错误:
ADOConnection := TADOConnection.create(nil);
Run Code Online (Sandbox Code Playgroud)
只是想知道这种行为背后的原因,即为什么在设计时保留组件时没有错误?
小智 4
如果释放组件,则其所有者中的相应字段将被清除。如果添加设计时ADOConnection,那么
ADOConnection.Free; // Frees ADOConnection and sets ADOConnection to nil
ADOConnection.Free; // Does nothing since ADOConnection is nil
Run Code Online (Sandbox Code Playgroud)
您可以通过将其捕获到变量中来看到这一点:
var c: TADOConnection;
c := ADOConnection;
c.Free; // Frees ADOConnection and sets ADOConnection to nil
c.Free; // Error: c is not set to nil
Run Code Online (Sandbox Code Playgroud)
ADOConnection即使是在设计时创建的,这也是行不通的。
下面是一个组件示例TButton,演示了您所看到的设计时组件的行为为何并非特定于设计时组件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
published
Button: TButton;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Assert(not Assigned(Button));
TButton.Create(Self).Name := 'Button'; // Button field gets set
Assert(Assigned(Button));
Button.Free; // Button field gets cleared
Assert(not Assigned(Button));
Button.Free; // Okay, Free may be called on nil values
end;
end.
Run Code Online (Sandbox Code Playgroud)