如何引用在"with"语句中创建的对象?

Flá*_*iro 2 delphi with-statement

我在运行时创建嵌套组件.如何Parent在一个子组件中分配子组件的属性with

with Tspanel.Create(categorypanel) do
begin
  parent:=categorypanel;  // categorypanel, is a declared variable
  height:=30;
  visible:=true;

  button1 := tsbutton.Create();
  // Here is my problem! I want the parent to be the
  // panel I've created with the "with tspanel.create(...)"
  button1.Parent := ...
end;
Run Code Online (Sandbox Code Playgroud)

我的目标是不为每个组件声明变量.

Dav*_*nan 8

你不能用with声明做你想做的事.无法命名作为with语句主题的对象.

请改用局部变量.例如:

var
  Panel1: TPanel
  Button1: TButton;
....
Panel1 := TPanel.Create(Form1);
Panel1.Parent := Form1;
Button1 := TButton.Create(Panel1);
Button1.Parent := Panel1;
Run Code Online (Sandbox Code Playgroud)

作为一个额外的好处,您可以删除这些with语句,这些语句是任何代码的范围.