Assigned vs <> nil

2019-02-05 16:03发布

Is there any difference between If Assigned(Foo) and If (Foo <> nil)? If So, when should they each be used?

1条回答
我命由我不由天
2楼-- · 2019-02-05 16:38

It is almost the same thing. The official documentation states

Assigned(P) corresponds to the test P<> nil for a pointer variable, and @P <> nil for a procedural variable.

So, if P is an ordinary pointer, then P <> nil and Assigned(P) are exactly equivalent. On the other hand, if P is some procedure, then

var
  p: TNotifyEvent = nil;

procedure TForm1.FormCreate(Sender: TObject);
begin
  if Assigned(p) then
    p(Self);
end;

will work, as will

procedure TForm1.FormCreate(Sender: TObject);
begin
  if @p <> nil then
    p(Self);
end;

but

procedure TForm1.FormCreate(Sender: TObject);
begin
  if p <> nil then
    p(Self);
end;

will not even compile. Hence, the conclusion is that P <> nil and Assigned(P) are exactly equivalent every time both works!

查看更多
登录 后发表回答