gpt4 book ai didi

delphi - TStringList - 奇怪的行为

转载 作者:行者123 更新时间:2023-12-03 15:07:59 26 4
gpt4 key购买 nike

Delphi 1 16 位(是的,它很旧,但运行良好)

一些示例代码:

procedure TForm1.Button1Click(Sender: TObject);
var
SL: TStringList;
begin

SL := TStringList.Create;
SL.Sorted := True;
SL.Duplicates := dupIgnore;

SL.AddObject('A', TObject(100));
SL.AddObject('A', TObject(999));
ShowMessage(IntToStr(LongInt(SL.Objects[0]))); {A}

SL.Free;

end;

我正在使用对象字段来存储长整型(一个黑客,是的,但它完成了工作)。无论如何,在上面的 A 行,我希望 ShowMessage 显示 100,而不是显示 999(即使设置了 dupIgnore)。我在这里错过了什么吗?或者它应该这样工作(我希望字符串列表忽略 999)?

最佳答案

刚刚在 Delphi 2009 中测试 - 它显示 100(根据 Delphi 2009 关于重复和 dupIgnore 的文档,它应该显示 100)。

可能是 Delphi 1 的错误。

<小时/>

已更新

@Sertac Akyuz:是的,这似乎是真的。 Google shows旧的 Delphi 版本具有以下 TStringList.Add 和 TStringList.AddObject 方法的实现:

function TStringList.Add(const S: string): integer;
begin
if not Sorted then
Result := FCount
else
if Find(S, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(SDuplicateString, 0);
end;
InsertItem(Result, S);
end;

function TStrings.AddObject(const S: string; AObject: TObject): Integer;
begin
Result := Add(S);
PutObject(Result, AObject);
end;

当前(Delphi 2009)的实现是:

function TStringList.Add(const S: string): Integer;
begin
Result := AddObject(S, nil);
end;

function TStringList.AddObject(const S: string; AObject: TObject): Integer;
begin
if not Sorted then
Result := FCount
else
if Find(S, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(@SDuplicateString, 0);
end;
InsertItem(Result, S, AObject);
end;

看看差异。旧的实现可能被视为错误(内存泄漏等)或未记录的允许行为。无论如何,当前的实现没有问题。

关于delphi - TStringList - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4070947/

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