Delphi 为什么FindComponent在此上下文中不起作用?

Delphi 为什么FindComponent在此上下文中不起作用?,delphi,Delphi,当我在运行时创建组件时,FindComponent将无法工作。这是我的密码: var m : tmemo; begin m := tmemo.create(form1); m.parent := form1; m.name := 'mymemo'; m.align := alclient; if (tmemo(findcomponent('mymemo')) <> nil) then showmessage('this should happen') else showmessage

当我在运行时创建组件时,FindComponent将无法工作。这是我的密码:

var m : tmemo;
begin
m := tmemo.create(form1);
m.parent := form1;
m.name := 'mymemo';
m.align := alclient;
if (tmemo(findcomponent('mymemo')) <> nil) then showmessage('this should happen') else
showmessage('but this is what actually happens');
end;
我希望tmemofindcomponent'mymemo'会返回我刚刚创建的备忘录,但实际上它返回nil。为什么会这样?

FindComponent是TComponent的一种方法。它搜索它所调用的TComponent对象所拥有的组件

FindComponent在您的示例中不起作用,因为您在错误的所有者上调用它。这是它返回零的唯一方法

您创建的TMemo对象的所有者是Form1对象,但随后在Self对象中搜索TMemo。Form1和Self显然不是指向同一个对象,因此FindComponent返回nil的原因。您需要在Form1对象上调用FindComponent,例如:

变量 m:TMemo; 开始 m:=TMemo.CreateForm1; m、 父项:=Form1; m、 姓名:=“我的备忘录”; m、 Align:=alClient; 如果Form1.FindComponent'mymemo'为零,则 ShowMessage“这确实发生了” 其他的 ShowMessage“这不应该发生”; 终止
您是否只是在寻找If-then…?您的代码周围的上下文是什么,即您从何处调用它?