Delphi116位(是的,它很旧,但工作得很好)
一些示例代码:
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;我使用Object字段来存储长度(这是一个技巧,但它可以完成工作)。不管怎样,在上面的A行,我预计ShowMessage会显示100,而不是999 (即使设置了dupIgnore )。我是不是漏掉了什么?或者它应该这样工作(我预计字符串列表会忽略999)?
发布于 2010-11-02 01:10:50
刚刚在Delphi2009中测试过--它显示为100 (根据Delphi2009中关于副本和dupIgnore的文档,它应该显示为100 )。
可能是Delphi 1的bug。
已更新
@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;看到不同之处。旧的实现可能被视为错误(内存泄漏等)或未记录的允许行为。在任何情况下,当前的实现都没有这个问题。
发布于 2010-11-02 00:44:56
你不会错过任何东西的。这就是发生的事情。
AddObject首先调用Add,它返回列表中新的(或现有的)元素的索引。然后,它调用PutObject在该索引处分配对象值。文档中未指定与Duplicates属性相关的行为。
https://stackoverflow.com/questions/4070947
复制相似问题