当btn为NIL时为什么可以访问btn.Caption? [英] Why I can access btn.Caption when btn is NIL?
问题描述
为什么此代码不会崩溃? T
为零。如果 T
为 nil
,如何访问字幕
?
Why this code does not crash? T
is nil. How it is possible to access Caption
if T
is nil
?
procedure Crash;
VAR T: TButton;
begin
T:= NIL;
T.Caption:= ''; <---------- this works
end;
推荐答案
TButton
控件是Win32 Button控件的包装。它使用Windows消息传递系统对其进行操作。这样做的核心方法 TControl.Perform()
具有内置的防护措施,可以防止 Self
发送消息是 nil
:
The TButton
control is a wrapper around the Win32 Button control. It uses the Windows messaging system to operate upon it. And the core method for doing so, TControl.Perform()
, has a built in safeguard against sending messages if Self
is nil
:
function TControl.Perform(Msg: Cardinal; WParam: WPARAM; LParam: LPARAM): LRESULT;
var
Message: TMessage;
begin
Message.Msg := Msg;
Message.WParam := WParam;
Message.LParam := LParam;
Message.Result := 0;
if Self <> nil then // <-- here
WindowProc(Message);
Result := Message.Result;
end;
标题
是设置器使用非虚拟 TControl.GetText()
和 TControl.SetText()
方法,可以在 nil
对象,因为它们的功能依赖于发送各种消息( WM_GETTEXTLEN
和 WM_SETTEXT
)到控件,并且仅涉及局部变量或传递的参数。因此,当 nil
时,实际的对象不会被访问,因此不会崩溃。
Caption
is a property whose setter uses the non-virtual TControl.GetText()
and TControl.SetText()
methods, which can be safely called upon nil
objects, as their functionality rely on sending various messages (WM_GETTEXTLEN
and WM_SETTEXT
) to the control, and only involve local variables or passed parameters. So the actual object is not accessed when nil
, thus no crash.
这篇关于当btn为NIL时为什么可以访问btn.Caption?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!