Delphi:TImage.Create 导致访问冲突 [英] Delphi: TImage.Create causes Access violation
问题描述
我提前为一个新手问题道歉,但为什么我在下面的代码中出现访问冲突"错误(在Create(SelectorForm);"行上)?我尝试使用主窗体作为所有者,但没有任何区别.
I apologize in advance for a newbie question, but why do I get "Access violation" error with the code below (on the "Create(SelectorForm);" line)? I tried using the main form as the owner, but it didn't make any difference.
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;
推荐答案
问题是你正在有效地这样做:
The problem is that you are effectively doing this:
var
imageVariable: TImage;
begin
imageVariable.Create (ParentForm);
end;
这是错误的,因为正在对尚未分配的变量调用Create"方法.
Which is wrong because "Create" method is being called on the variable which hasn't been assigned yet.
你应该这样做:
var
imageVariable: TImage;
begin
imageVariable := TImage.Create (ParentForm);
try
//use the object
finally
FreeAndNil (imageVariable);
end;
end;
或者更具体地说,在您的代码中:
Or more specifically in your code:
for Loop := 1 to 10 do
begin
ArrayOfImages[Loop] := TImage.Create (Self);
end;
别忘了释放对象
接受@andiw 的评论并收回释放对象的提示.接受@Gerry 的评论并使用 Self 作为所有者.
Accepting @andiw's comment and taking back the tip of freeing objects. Accepting @Gerry's comment and using Self as owner.
这篇关于Delphi:TImage.Create 导致访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!