问题
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