【问题标题】:Create objects in runtime and work with them在运行时创建对象并使用它们
【发布时间】:2015-03-09 09:45:45
【问题描述】:

我的程序运行时创建的对象有问题

首先我创建 n 个对象(假设 n := 3)

for i:=0 to n-1 do
  begin
    With TGauge.Create(Form1) do
      begin
        Parent  := Form1;  // this is important
        Left    := 20;     // X coordinate
        Top     := 20+i*45;     // Y coordinate
        Width   := 250;
        Height  := 20;
        Kind    := gkHorizontalBar;
        Name    := 'MyGauge'+IntToStr(i);
        //.... 
        Visible := True;
      end;
  end;

这 3 个对象已创建并在表单中可见。现在我想改变它的属性,但是每当我尝试访问这些创建的对象时,我只会得到 ​​p>

EAccessViolation

例如,当我尝试获取一个对象的名称时

g := Form1.FindComponent('MyGauge0') as TGauge;
Form1.Label1.Caption:=g.Name;

【问题讨论】:

  • 最好将它们的引用存储到一个数组中,或者一个类似集合的列表中。
  • 对于 n=3,你有 3 个对象,而不是 4 个。
  • @Inspired 感谢您的通知。只是拼写错误
  • “这很重要”我认为你的代码所有都很重要:-)

标签: delphi reference runtime components delphi-7


【解决方案1】:

您的代码失败,因为FindComponent 返回nil。这是因为Form1 对象不拥有具有该名称的组件。从这里很难说为什么会如此。

但是,使用名称查找是解决问题的错误方法。不要使用名称来指代组件。将它们的引用保存在一个数组中。

var
  Gauges: array of TGauge;
....
SetLength(Gauges, N);
for I := 0 to N-1 do
begin
  Gauges[i] := TGauge.Create(Form1);
  ....
end;

然后您可以使用该数组引用控件。

我还要评论说,您指的是Form1 全局对象很奇怪。在TForm1 类中执行此操作可能会更好,因此能够使用隐式Self 实例。

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多