我经常发现我需要“调整”TStringList
的大小以恰好容纳 N 个元素,要么向列表中添加额外的空字符串,要么删除不需要的字符串。
在 C++ STL 容器上,我可以使用 resize
方法,但由于该方法似乎不存在,因此我通常会执行类似的操作(警告:伪代码!)。
list.beginUpdate;
while list.Count < requiredSize do
begin
list.add('');
end;
while list.Count > requiredSize do
begin
list.delete(list.count-1);
end;
list.endUpdate;
是否有一种我忽略的更简单的方法?
最佳答案
从TStringList.Assign
的实现来看,没有更好的方法来做到这一点。他们基本上调用 Clear
并一一添加字符串。
您当然应该将代码放入实用方法中:
procedure ResizeStringList(List : TStrings; ANewSize: Integer);
begin
...
end;
或者您可以使用类帮助器使您的方法看起来像是 TStringList
本身的一部分。
关于delphi - 调整 TStringList 大小的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21088346/