当btn为NIL时为什么可以访问btn.Caption? [英] Why I can access btn.Caption when btn is NIL?

查看:63
本文介绍了当btn为NIL时为什么可以访问btn.Caption?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码不会崩溃? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆