TStringList计数返回负数

时间:2018-04-02 17:58:51

标签: lazarus freepascal tstringlist

我想使用count属性计算TStringList中的项目数(字符串)。 TStringList.Count给我返回“-307586000”为什么?

这是我在拉撒路的代码:

let newuser = {
    userId: info.userId,
    id: info.id,
    title: info.title,
    body: info.body
}

Thx家伙。

1 个答案:

答案 0 :(得分:2)

您需要将list.Create;更改为list := TStringList.Create;当您通过对象变量而不是类类型调用构造函数时,构造函数会像普通方法一样被调用。您实际上并未创建任何TStringList对象,因此调用list.Add()list.Count是未定义的行为。你很幸运,你的代码并没有简单地崩溃。

此外,请勿忘记在使用list.Free;后致电list

试试这个:

procedure Test;
var
  list: TStringList;
  vrai: boolean;
  nCol, i: integer;
begin
  vrai := true;
  list := TStringList.Create;
  try
    nCol := 5;
    for i := 0 to nCol-1 do
    begin
      if vrai then
      begin
        list.Add(IntToStr(i));
        ShowMessage(IntToStr(list.Count));
      end;
    end;
  finally
    list.Free;
  end;
end;