TObjectList<T>.Contains causes Access Violation in Delphi 2009

时光总嘲笑我的痴心妄想 提交于 2019-12-08 02:28:00

问题


In Delphi 2009, I had no major problems with Generics so far (using Generics.Collections lists, with no special Generics features).

Now I found this code will cause an AV in the line which accesses MyList.Contains.

The error disappears if I declare TMyList = class(TList<TMyEntry>);

Should I avoid TObjectList<T> or is something else in my code causing this error?

type
  TMyEntry = class(TStringlist);
  TMyList = class(TObjectList<TMyEntry>);

procedure TListTests.TestAV;
var
  Entry: TMyEntry;
  MyList: TMyList;
begin
  MyList := TMyList.Create;
  try
    Entry := TMyEntry.Create;

    MyList.Add(Entry);

    Assert(MyList.Contains(Entry));  // <--- AV

  finally
    MyList.Free;
  end;
end;

回答1:


This is the fix, based on the linked answer:

change

MyList := TMyList.Create;

to

MyList := TMyList.Create(TComparer<TMyEntry>.Default);


来源:https://stackoverflow.com/questions/9940082/tobjectlistt-contains-causes-access-violation-in-delphi-2009

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!