4

我提前为一个新手问题道歉,但为什么我会在下面的代码中出现“访问冲突”错误(在“Create(SelectorForm);”行)?我尝试使用主窗体作为所有者,但没有任何区别。

var
  SelectorForm: TSelectorForm;
  ArrayOfImages: Array [1..10] of TImage;

implementation

procedure TSelectorForm.FormCreate(Sender: TObject);
var
  Loop: Byte;
begin
  for Loop := 1 to 10 do
  begin
    with ArrayOfImages[Loop] do
    begin
      Create(SelectorForm);
    end;
  end;
end;
4

2 回答 2

17

问题是您正在有效地执行此操作:

var
  imageVariable: TImage;
begin
  imageVariable.Create (ParentForm);
end;

这是错误的,因为正在对尚未分配的变量调用“创建”方法。

你应该做这个:

var
  imageVariable: TImage;
begin
  imageVariable := TImage.Create (ParentForm);
  try
    //use the object
  finally
    FreeAndNil (imageVariable);
  end;
end;

或者更具体地说,在您的代码中:

for Loop := 1 to 10 do
begin
  ArrayOfImages[Loop] := TImage.Create (Self);
end;

不要忘记释放对象

编辑:接受@andiw 的评论并收回释放对象的提示。EDIT2:接受@Gerry 的评论并使用 Self 作为所有者。

于 2009-06-24T05:58:57.390 回答
0

There are a lot of problems with the above code. (don't use the "With" like that for a start, don't use a Byte for your loop var)

My assumption is that you ultimately want an array of instances of TImage's created with a form as the parent.

so based on that assumtion...you want something like (untested)

var
  ArrayOfImages: Array [0..9] of TImage;  
  i : integer;
begin
  for i := 0 to 9 do
  begin
    ArrayOfImages[i] := TImage.Create(theForm);
  end;

end;

Now note, you will be responsible for cleaning up the array when you are finished using it, you will need to call free on each of the Image instances.

于 2009-06-24T06:08:03.367 回答