首页 > 解决方案 > Transform a string to an object pointer?

问题描述

I have a string 'MyButton'.

How can I get the OBJECT MyButton from the STRING 'MyButton', so that I could write:

MyButton.Caption := 'My new Caption';

This would change the caption of the TButton MyButton object instance.

标签: delphirttidelphi-10.3-rio

解决方案


If the component has an Owner assigned (as all components placed at design-time do), then you can use the Owner's FindComponent() method, eg:

procedure TMyForm.DoSomething;
var
  Cmp: TComponent;
begin
  Cmp := Self.FindComponent('MyButton');
  if Cmp <> nil then
    (Cmp as TButton).Caption := 'My new Caption';
end;

推荐阅读