问题描述
我解决了我的问题,但我需要知道为什么这个问题引起了我!!
I solved my problem but I need to know why this problem raised to me ?!
我写了一个项目,将文件加载到listBox,然后一个个地删除字符串,
I write a project that load file to listBox then delete the strings one by one,
但是当我删除listBox字符串时,此异常引发了我!
but when I delete listBox strings this exception raised to me!
列表索引超出范围(5)!
我键入此for循环以读取列表框并删除字符串:
I type this for loop to read list box and delete strings:
for i := 0 to ListBox3.Count -1 do
begin
ShowMessage(ListBox3.Items[i]);
ListBox3.items.Delete(i);
end;
我的问题通过在for-loop语句中做一些改动来解决
and my problem solved by do a little change in for-loop statement
for i := ListBox3.Items.Count - 1 downto 0 do
begin
ShowMessage(ListBox3.Items[i]);
ListBox3.items.Delete(i);
end;
为什么第一个语句引发异常,而第二个语句可以正常工作?
Why the first statement raised an exception, and the second one work fine ?
推荐答案
通过删除前进的项目,您可以切断正在站立的分支. :-)在循环开始之前,循环的上限仅计算一次,并且如果您删除项目,则列表中的内容现在比计算边界时要少.
By deleting items moving forward, you're cutting the branch off that you're standing on. :-) The upper bounds of the loop is only evaluated once, before the loop begins, and if you delete items there are now fewer in the list than there were when the bound was calculated.
- 评估
- 循环极限(例如,
List.Count - 1
= 5).有效索引为[0..4] - 循环开始,您检索List [0]并将其删除.列表计数= 4界限仍然是5
- 索引增加,您检索并删除List [1].列表计数= 3,界限仍为5
- 索引增加,您检索并删除列表[2].列表计数= 2,界限仍为5.
- 索引增加,您检索列表[3]-糟糕!列表中只有2个项目,现在位于索引[0..1]-列表索引超出范围(3).
- Loop limit is evaluated (for example,
List.Count - 1
= 5). Valid indexes into it are [0..4] - The loop starts, and you retrieve List[0] and delete it. List Count = 4,bounds is still 5
- The index is incremented, you retrieve and delete List[1]. List Count = 3, bounds is still 5
- The index is incremented, you retrieve and delete List[2]. List Count = 2, bounds is still 5.
- The index is incremented, you retrieve List[3] - Oops! There are only 2 items in the list, now at indexes [0..1] - List index out of bounds(3).
通过向后迭代,即使边界仍仅在开始时计算,您仍要从末尾删除项目并同时减少计数.
By iterating backwards, even though the bounds is still only calculated at the beginning, you're removing the items from the end and decrementing the count at the same time.
- 界限为5,则检索List [4]并将其删除. Count现在是4,界限仍然是5
- 索引递减,然后检索List [3]并将其删除.计数现在是3,界限仍然是5
- 索引递减,然后检索List [2]并将其删除. Count现在是2,界限仍然是5.
- 索引递减,并且您检索和删除List [1].计数现在为1,界限仍然为5.
- 索引递减,然后您检索并删除列表[0].列表现在为空,但是我们已经达到循环的终止条件(
downto 0
),并且循环安全退出.
- Bounds is 5, and you retrieve List[4] and delete it. Count is now 4, bounds is still 5
- Index is decremented, and you retrieve List[3] and delete it. Count is now 3, bounds is still 5
- Index is decremented, and you retrieve List[2] and delete it. Count is now 2, bounds is still 5.
- Index is decremented, and you retrieve and delete List[1]. Count is now 1, bounds is still 5.
- Index is decremented, and you retrieve and delete List[0]. List is now empty, but we've reached the terminating condition of the loop (
downto 0
) and the loop exits safely.
这篇关于删除项目时超出范围列出索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!