问题描述
我使用的是 Delphi 10.3 Community Edition,面向 Windows 32 位。
我正在编写一个接口类型。它的类在内部使用 TList<T>
(和一些其他对象)。为了避免编写多个传递单行方法,我使用 implements
关键字进行委托,如下所示:
program MRE;
{$APPTYPE CONSOLE}
uses
System.Generics.Collections;
type
IMyList = interface
['{8483DB08-57EA-40D0-BFCE-5E39804CA15B}']
function Add (const ACard: Cardinal): Integer;
function GetEnumerator: TList<Cardinal>.TEnumerator;
end;
TMyList = class (TInterfacedObject,IMyList)
constructor Create;
destructor Destroy; override;
private
FCards: TList<Cardinal>;
public
property Cards: TList<Cardinal>
read FCards
implements IMyList;
end;
constructor TMyList.Create;
begin
FCards := TList<Cardinal>.Create;
end;
destructor TMyList.Destroy;
begin
FCards.Free
end;
begin
var Test: IMyList := TMyList.Create;
Test.Add (3);
for var c in Test do
WriteLn (c);
ReadLn
end.
这工作正常并按预期打印 3。
然而,当我在更复杂的程序版本中遇到奇怪的崩溃时,我能够将错误提炼到类型的声明。只需添加一行(类型声明之间的任何位置):
type
TCardList = TList<Cardinal>; { **** this isn't even used anywhere! }
代码仍然可以编译,但应用程序现在因访问冲突('写入地址 0x004ee838')而崩溃。这不仅仅是对 Add()
的调用。当您删除它时,它仍然会在 for
循环尝试获取枚举器时崩溃。
是否有一些我在这里遗漏的对委托的奇怪限制,或者这可能是编译器缺陷?
编辑:根据评论中的要求,这里再次添加了相同的代码,其中已添加触发崩溃的单行:
program MRE;
{$APPTYPE CONSOLE}
uses
System.Generics.Collections;
type
TCardList = TList<Cardinal>; { **** this isn't even used anywhere! }
IMyList = interface
['{8483DB08-57EA-40D0-BFCE-5E39804CA15B}']
function Add (const ACard: Cardinal): Integer;
function GetEnumerator: TList<Cardinal>.TEnumerator;
end;
TMyList = class (TInterfacedObject,IMyList)
constructor Create;
destructor Destroy; override;
private
FCards: TList<Cardinal>;
public
property Cards: TList<Cardinal>
read FCards
implements IMyList;
end;
constructor TMyList.Create;
begin
FCards := TList<Cardinal>.Create;
end;
destructor TMyList.Destroy;
begin
FCards.Free
end;
begin
var Test: IMyList := TMyList.Create;
Test.Add (3);
for var c in Test do
WriteLn (c);
ReadLn
end.
这会产生上面提到的崩溃。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)