【问题标题】:How do I refer to an object created in a "with" statement?如何引用在“with”语句中创建的对象?
【发布时间】:2013-06-03 20:58:04
【问题描述】:

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

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;

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

【问题讨论】:

  • '我的目标是不为每个组件声明变量' - 为什么不呢?

标签: delphi with-statement


【解决方案1】:

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

改为使用局部变量。例如:

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

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

【讨论】:

  • "With" 很少值得。麻烦多过它的价值。
  • ...您将能够在 IDE 中调试命名对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2012-02-28
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多