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

时间:2013-06-07 14:02:02

标签: 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;

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

1 个答案:

答案 0 :(得分:8)

使用with语句无法执行所需操作。无法命名作为with语句主语的对象。

改用局部变量。例如:

var
  Panel1: TPanel
  Button1: TButton;
....
Panel1 := TPanel.Create(Form1);
Panel1.Parent := Form1;
Button1 := TButton.Create(Panel1);
Button1.Parent := Panel1;

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