8

为什么在执行下面的代码时会引发 EAccessViolation?

uses
  Generics.Collections;
  ...

var
  list: TList<TNotifyEvent>;
  ...

begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;

procedure myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;
4

4 回答 4

5

它看起来像一个错误。

如果您使用调试 dcu 进行编译(通常不要这样做,除非您想失去理智!)您会看到对比较器的调用出错了。比较函数的第三个值(可能是可选的)未设置并导致访问冲突。

因此,您可能无法将方法指针放在通用列表中。

好的,以下工作:

uses
  Generics.Defaults;

type
  TForm4 = class(TForm)
    ...
  private
    procedure myNotifyEvent(Sender: TObject);
  end;

TComparer<T> = class (TInterfacedObject, IComparer<T>)
public
  function Compare(const Left, Right: T): Integer;
end;

implementation

uses
  Generics.Collections;

var
  list: TList<TNotifyEvent>;
begin
  list := TList<TNotifyEvent>.Create(TComparer<TNotifyEvent>.Create);
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);
  finally
    FreeAndNil(list);
  end;
end;

procedure TForm4.myNotifyEvent(Sender: TObject);
begin
  ShowMessage('event');
end;

{ TComparer<T> }

function TComparer<T>.Compare(const Left, Right: T): Integer;
begin
  Result := 0;
end;

您必须定义自己的比较器,并且可能具有更多的智能;-)。

于 2008-11-14T11:59:02.710 回答
3

访问冲突是由缺少比较器引起的。我怀疑这已在补丁中修复,但如果您使用 TObjectList,问题仍然存在(至少在 Delphi 2009 中),所以我只是用最简单的解决方案进行更新:

TList<TNotifyEvent>.Create(TComparer<TNotifyEvent>.Default);

或者在我的情况下

TObjectList<TNotifyEvent>.Create(TComparer<TNotifyEvent>.Default);
于 2010-01-14T19:13:32.123 回答
1

是否可以将自定义比较器传递给TList<T>?我面前没有D2009,所以不能尝试。

于 2008-11-14T12:19:27.757 回答
0

上面的代码用于 TForm1 ...

uses 
  Generics.Collections;

procedure TForm1.Button1Click(Sender: TObject);
var
  list: TList<TNotifyEvent>;
begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;
procedure TForm1.myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;
于 2008-11-14T11:50:04.260 回答