gpt4 book ai didi

delphi - 为什么 TList.Remove() 会产生 EAccessViolation 错误?

转载 作者:行者123 更新时间:2023-12-03 14:47:45 25 4
gpt4 key购买 nike

为什么执行下面的代码时会引发 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;

最佳答案

看起来像是一个错误。

如果您使用 debug 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;

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

关于delphi - 为什么 TList.Remove() 会产生 EAccessViolation 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com