【问题标题】:TStringList count returns negative number [duplicate]TStringList计数返回负数[重复]
【发布时间】:2018-04-02 17:58:51
【问题描述】:
我想使用 count 属性计算 TStringList 中项目(字符串)的数量。 TStringList.Count 返回“-307586000”为什么?
这是我在 Lazarus 中的代码:
procedure Test;
var
list: TStringList;
vrai: boolean;
nCol, i: integer;
begin
vrai := true;
list.Create;
nCol := 5;
for i := 0 to nCol-1 do
if vrai then
begin
list.Add(intToStr(i));
showmessage(IntToStr(list.Count));
end;
end;
谢谢各位。
【问题讨论】:
标签:
lazarus
freepascal
tstringlist
【解决方案1】:
您需要将list.Create; 更改为list := TStringList.Create; 当您通过对象变量而不是类类型调用构造函数时,构造函数会像普通方法一样被调用。您实际上并没有创建任何 TStringList 对象,因此调用 list.Add() 和 list.Count 是未定义的行为。你很幸运,你的代码没有简单地崩溃。
另外,当您使用完list 后,别忘了致电list.Free;。
试试这个:
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;