gpt4 book ai didi

Delphi TPair 异常

转载 作者:行者123 更新时间:2023-12-03 15:06:25 24 4
gpt4 key购买 nike

我有这个尖峰来测试 TPair。您可以在新的 Delphi XE Con​​sole 应用程序上复制+粘贴。我已经标记了异常(exception)的行:

Project Project1.exe raised exception class EAccessViolation with message 'Access violation at address 0045042D in module 'Project1.exe'. Read of address A9032D0C.

有什么想法吗?

谢谢。

program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils,
Generics.Defaults,
Generics.Collections;

type
TProduct = class
private
FName: string;
procedure SetName(const Value: string);
published
public
property Name: string read FName write SetName;
end;

type
TListOfProducts = TObjectDictionary<TProduct, Integer>;

{ TProduct }

procedure TProduct.SetName(const Value: string);
begin
FName := Value;
end;


var
MyDict: TListOfProducts;
MyProduct1: TProduct;
MyProduct2: TProduct;
MyProduct3: TProduct;
APair: TPair<TProduct, Integer>;
aKey: string;

begin
try
MyDict := TListOfProducts.Create([doOwnsKeys]);
MyProduct1 := TProduct.Create;
MyProduct1.Name := 'P1';
MyProduct2 := TProduct.Create;
MyProduct2.Name := 'P2';
MyProduct3 := TProduct.Create;
MyProduct3.Name := 'P3';

MyDict.Add(MyProduct1, 1);
MyDict.Add(MyProduct2, 2);
MyDict.Add(MyProduct3, 3);

APair := MyDict.ExtractPair(MyProduct1);
Writeln(APair.Key.Name); // <--- Error is Here.
Writeln(IntToStr(APair.Value));

Readln(aKey);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

最佳答案

这是一个 Delphi 错误。 TDictionary<TKey,TValue>.ExtractPair不分配 Result .

RRUZ 找到了bug in QC .

代码如下:

function TDictionary<TKey,TValue>.ExtractPair(const Key: TKey): TPair<TKey,TValue>;
var
hc, index: Integer;
begin
hc := Hash(Key);
index := GetBucketIndex(Key, hc);
if index < 0 then
Exit(TPair<TKey,TValue>.Create(Key, Default(TValue)));

DoRemove(Key, hc, cnExtracted);
end;

Result当调用 DoRemove 时应分配已制作完成。

解决这个错误非常困难。 ExtractPair是在不破坏 key 的情况下从字典中获取项目的唯一方法,因此您必须调用它。但由于它不会返回提取的项目,因此您需要首先读取该项目,记住该值,然后调用 ExtractPair .

关于Delphi TPair 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5861857/

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