德尔福。如何获取指向动态创建的对象的指针
我想通过指针访问组件,而不是使用 FindComponent 进行搜索。以下分配适用于放置在表单上的组件,但不适用于动态创建的组件。例如:
var
Pbtn: ^TButton;
Button2: TButton;
begin
Pbtn := @Button1;
Showmessage(pbtn.caption); // works well
Button2 := TButton.Create(Form2);
Pbtn := @Button2;
Showmessage(pbtn.caption); // not work
...
I would like to access components via pointers instead of searching using FindComponent. The following assignment works for components placed on the Form, but not for dynamically created components. For example:
var
Pbtn: ^TButton;
Button2: TButton;
begin
Pbtn := @Button1;
Showmessage(pbtn.caption); // works well
Button2 := TButton.Create(Form2);
Pbtn := @Button2;
Showmessage(pbtn.caption); // not work
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类类型是引用类型,因此类类型的对象实例已经表示为指针。不要使用
^
/@
来引用这些对象(这只会引用指针本身,在大多数情况下很少需要),例如:A class type is a reference type, so object instances of a class type are already represented as pointers. Don't use
^
/@
to refer to these objects (that will only refer to the pointers themselves, which is rarely ever needed in most situations), eg:你的代码工作得很好。
但是为什么示例中的第二条消息不返回任何文本呢?这是因为当您动态创建 TButton 时,不会为其标题分配任何值,因此第二条消息返回一个空字符串。
如果您更改代码以将特定标题分配给第二个按钮,您会发现它工作得很好
但是为什么设计时放置的按钮上有一个标题。这是因为 Delphi IDE 将标题设置为与表单上放置的组件名称相同。这样做只是为了方便 Delphi 用户。
Your code works just fine.
But why the second message in your example doesn't return any text then? That is because when you dynamically create a TButton no value is assigned to its caption and therefore your second message returns an empty string.
If you change your code to assign a specific caption to your second Button you will see that it works just fine
But why there is a caption on design-time placed button. That is because Delphi IDE sets the caption to be same as the component name that was placed on the form. This is done just out of convenience to the Delphi user.