嘗試用循環遍歷 `ListBox.Items` 並調用 `RemoveAt` 或 `Remove` 清空項目時,常遇到兩類問題:
// 錯誤 1:for 循環索引錯位
for (int i = 0; i < ListBox1.Items.Count; i++)
ListBox1.Items.RemoveAt(i);
// 錯誤 2:foreach 修改集合拋異常
foreach (ListItem li in ListBox1.Items)
ListBox1.Items.Remove(li); // 執行到第 2 次迭代即拋出異常
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
ListBox1.Items.RemoveAt(i);
倒序刪除不影響未處理項目的索引,最簡潔高效。
ListBox1.Items.Clear();
`ListItemCollection` 內建 `Clear()` 方法,一行代碼解決,官方推薦做法。
while (ListBox1.Items.Count > 0)
ListBox1.Items.RemoveAt(0);
每次刪除首項,索引固定為 0,邏輯清晰但比 `Clear()` 慢。
var items = new ListItem[ListBox1.Items.Count];
ListBox1.Items.CopyTo(items, 0);
foreach (var li in items)
ListBox1.Items.Remove(li);
原文提供的遞歸迭代器雖能工作,但存在嚴重缺陷:
切勿在生產代碼中使用該遞歸方案。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 單純清空所有項 | `ListBox.Items.Clear()` | 語義明確、性能最優、框架原生 |
| 條件性刪除部分項 | 倒序 `for` 循環 | 避免索引錯位、無額外分配 |
| 需保留刪除前副本 | 複製到 `List<ListItem>` 再操作 | 安全遍歷、靈活過濾 |