Delphi   发布时间:2022-04-10  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了delphi – 为什么TList.Remove()会产生EAccessViolation错误?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么在执行下面的代码时会引发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;

解决方法

它看起来像一个bug.

如果使用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错误?全部内容,希望文章能够帮你解决delphi – 为什么TList.Remove()会产生EAccessViolation错误?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。