问题来源: http://www.cnblogs.com/del/archive/2008/05/21/1101470.html#1204455
unit Unit1;

interface

uses
  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);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  BtnGlobal: TButton; {定义一个全局的对象(TButton)变量}

procedure TForm1.Button1Click(Sender: TObject);
var
  BtnLocal: TButton;  {定义一个局部的对象(TButton)变量}
begin
  {"对象" 本身就是指针, 它指向对象数据存在的位置;}
  {"@对象" 是指向对象的指针, 它指向 "对象" 变量本身, 如果 "对象" 变量存在, 它肯定是存在的}
  {下面 4 行代码能获取指针的地址, 如果结果为 0 则表示对象还没有赋值, 也就是为 nil}
  ShowMessage(IntToStr(Integer(BtnGlobal)));  {0;}
  ShowMessage(IntToStr(Integer(@BtnGlobal))); {4607236}
  ShowMessage(IntToStr(Integer(BtnLocal)));   {0}
  ShowMessage(IntToStr(Integer(@BtnLocal)));  {1242560}

  {在没有给对象(BtnGlobal、BtnLocal)赋值以前, Assigned(对象)应该返回 False}
  ShowMessage(BoolToStr(Assigned(BtnGlobal), True));  {False}
  ShowMessage(BoolToStr(Assigned(BtnLocal), True));   {False}

  {因为对象变量已经存在, 所以指向对象变量的 "@对象" 也不会为 nil}
  ShowMessage(BoolToStr(Assigned(@BtnGlobal), True)); {True}
  ShowMessage(BoolToStr(Assigned(@BtnLocal), True));  {True}


  {赋值以后...}
  BtnGlobal := TButton(Sender);
  BtnLocal  := TButton(Sender);

  ShowMessage(BoolToStr(Assigned(BtnGlobal), True));  {True}
  ShowMessage(BoolToStr(Assigned(BtnLocal), True));   {True}

  ShowMessage(BoolToStr(Assigned(@BtnGlobal), True)); {True}
  ShowMessage(BoolToStr(Assigned(@BtnLocal), True));  {True}
end;

{因为 Delphi 会给部分类型的局部变量一个无用的默认值, 所以会出现下面情形}
procedure TForm1.Button2Click(Sender: TObject);
var
  Btn: TButton;
begin
  ShowMessage(IntToStr(Integer(Btn))); {15012064; 如果不注释掉下面一句, 这里会是 0}
  //ShowMessage(IntToStr(Integer(@Btn)));  {1242560}

  {我的结论是: 用 Assigned 判断一个没有初始化的局部变量是不可靠的, 这应该算个 Bug}
  {解决方案: 如果程序中确需这样的判断, 那就先初始化局部变量为空, 譬如:}
  Btn := nil;
  ShowMessage(BoolToStr(Assigned(Btn), True));  {False}

  Btn := TButton(Sender);
  ShowMessage(BoolToStr(Assigned(Btn), True));  {True}
end;

end.

posted on 2008-05-21 11:08  万一  阅读(2404)  评论(2编辑  收藏  举报