是否有良好的做法,如果在循环TStringList项时避免了越界索引错误? [英] Are there good practices if any avoiding out of bounds index error when looping TStringList items?
本文介绍了是否有良好的做法,如果在循环TStringList项时避免了越界索引错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
:)
第一件事,我的代码
procedure TForm1.Button3Click(Sender: TObject);
var tempId,i:integer;
begin
tempId:=strtoint(edit5.Text);
plik:=TStringList.Create;
plik.LoadFromFile('.\klienci\'+linia_klient[id+1]+'.txt');
if (plik.Count=1) then
begin
label6.Caption:='then';
if (tempId=StrToInt(plik[0])) then
begin
Label6.Caption:='Zwrócono';
plik.Delete(0);
end
end
else
for i:=0 to plik.Count-2 do
begin
if (tempId=StrToInt(plik[i])) then
begin
Label6.Caption:='Zwrócono';
plik.Delete(i);
end;
end;
plik.SaveToFile('.\klienci\'+linia_klient[id+1]+'.txt');
plik.Free;
end;
- 当
for i:=0 to plik.Count-2 do
时,我可以删除任何元素,但不能删除 最后. - 当
for i:=0 to plik.Count-1 do
时,我可以删除没有 但从头到尾.因为否则列表索引将超出范围. - When
for i:=0 to plik.Count-2 do
I can delete any element but not last. - When
for i:=0 to plik.Count-1 do
I can delete any element without but from end to start. Because otherwise List index out of bounds.
怎么回事?如何安全搜索并从TStringList中删除元素?
What's going one? How can I safety search and remove elements from TStringList?
推荐答案
从列表中删除intem时,您想使用downto
循环,即
When deleting intems from list you want to use downto
loop, ie
for i := plik.Count-1 downto 0 do
begin
if (tempId=StrToInt(plik[i])) then
begin
Label6.Caption:='Zwrócono';
plik.Delete(i);
end;
end;
这可以确保,如果删除项目,则循环索引在从列表末尾向列表末尾移动时仍保持有效.
This ensures that if you delete item, the loop index stays valid as you move from the end of the list dowards beginning of the list.
这篇关于是否有良好的做法,如果在循环TStringList项时避免了越界索引错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文