加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi:TImage.Create导致访问冲突

发布时间:2020-12-15 09:42:54 所属栏目:大数据 来源:网络整理
导读:我提前为新手问题道歉,但为什么我的代码出现“访问冲突”错误(在“Create(SelectorForm);”行上)?我尝试使用主窗体作为所有者,但它没有任何区别. var SelectorForm: TSelectorForm; ArrayOfImages: Array [1..10] of TImage;implementationprocedure TSelec
我提前为新手问题道歉,但为什么我的代码出现“访问冲突”错误(在“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;

解决方法

问题是你实际上是这样做的:

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

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

你应该做这个:

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作为所有者.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读