Is there any difference between If Assigned(Foo)
and If (Foo <> nil)
? If So, when should they each be used?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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!