在声明一个Var Obj:TObject后,我怎么样判断一个对象变量确实引用了一个对象,以便调用Obj.method1,用obj=nil判断也不合适,因为即使没有执行Obj:=TObject.create;Obj也未必是空,除非申明变量的时候把Obj:=nil,但这样很繁琐。有什么好方法吗?

解决方案 »

  1.   

    Tests for a  nil (unassigned) pointer or procedural variable.UnitSystemCategorypointer and address routinesDelphi syntax:function Assigned(const P): Boolean;DescriptionUse 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.Note: Assigned can't detect a dangling pointer--that is, one that isn't nil but no longer points to valid data. For example, in the code example for Assigned, Assigned won't detect the fact that P isn't valid.
      

  2.   

    如果TObject是过程序或函数的内部变量, 系统会自动初始化和释放.所以不为空(nil).
    如果TObject是外部变量或全局变量, 系统不会自动初始化和释放.所以为空(nil).var
      Form1: TForm1;
      obj : TObject;
    implementation
    {$R *.DFM}procedure TForm1.Button1Click(Sender: TObject);
    var
      Obj2 : TObject;
    begin
      if Obj = nil then
        showmessage('obj1 is nill');
      if Obj2 = nil then
        showmessage('obj2 is nill');
    end;
      

  3.   

    if not Assigned(对象变量) then