delphi assigned函數的用法


if not Assigned(Modeless) then Assigned()什么意思!

 

assigned 是用來判斷某一指針(pointer)或過程引用是否為nil(空),如果為空則返回假(false)。

 

用法示例(防止窗體被實例化多次):

 

 

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;

 

var

  Form1: TForm1;

 

implementation

 

uses Unit2;

 

{$R *.dfm}

 

procedure TForm1.Button1Click(Sender: TObject);

begin

  if (Not assigned(form2)) then

  begin

    form2:=Tform2.Create(Self);

  end;

  form2.show;

end;

 

end.

 

-----------------------

unit Unit2;

 

interface

 

uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs;

 

type

  TForm2 = class(TForm)

    procedure FormClose(Sender: TObject; var Action: TCloseAction);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

 

var

  Form2: TForm2;

 

implementation

 

{$R *.dfm}

 

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);

begin

  Action:=caFree;

  form2:=nil;  //這句比較重要,窗體被釋放時,窗體變量並不會自動變空

end;

 

end.

 

很詳細呢,不過不是我的原創,我轉的,希望對你有用啦。。。。。

 

另一篇網絡文章

關於Delphi中的Assigned
2008-04-05 10:53

關於Delphi中的Assigned
 
function Assigned(var P): Boolean;

Description

Use Assigned to determine whether the pointer or procedure referenced by P is nil. P must be a variable reference of a pointer or procedural type. Assigned(P) corresponds to the test P<> nil for a pointer variable, and @P <> nil for a procedural variable.

Assigned returns False if P is nil, True otherwise.

檢查指針指向的參考變量或過程是否為nil

每次我通常的處理方法都是:

if assigned(frm) then frm.close;    但是當下次調用時就會出錯。為什么呢,直到咋天我才知道原因

frm.close;frm.free;   只是指定這塊內存可以重寫,並未釋放為NIL 因此當下次調用時即使frm.free已經

執行過assigned(frm)仍為TRUE;

正確的處理方法:

if assigned(frm) then
begin
    frm.close;
    frm:=nil;
end;

或:

if assigned(frm) then
begin
   frm.close;
   freeandnil(frm);
end;

freeandnil的說明:

procedure FreeAndNil(var Obj);

Description

Use FreeAndNil to ensure that a variable is nil after you free the object it references. Pass any variable that represents an object as the Obj parameter.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM