Remove& RemoveAtin和有什么不一样ListBox?
2 回答
好吧,首先,如果你有一个ListBox listBox;,那么listBox没有方法Remove或RemoveAt。它会是listBox.Items.Remove(...)或listBox.Items.RemoveAt(...)。我在这里假设您使用的是ListBoxin System.Windows.Forms。
Remove现在,和之间的区别在于RemoveAt一个需要从列表中删除的项目,另一个需要一个索引。
为了更清楚,让我们创建一个List<int> list = new List<int>(new int[] { 10, 20, 30, 40 });. 由于C# 中的所有内容都是从零开始的,因此列表中索引 0 处10的值是 ,索引 1 处的值是20,等等。
Lists,就像ObjectCollections 一样,拥有Remove和RemoveAt方法。在我们的简单列表的情况下,调用list.Remove(20);将删除20它在列表中找到的第一个出现。list将与被删除后{ 10, 30, 40 }的元素一起结束。20
如果我们不调用Removeon list,而是调用list.RemoveAt(1);,它会对列表做同样的事情。我们正在删除索引处1的列表元素:在这种情况下,20.
我正在计算 RemoveAt 和 Remove 函数之间的差异。查看以下代码段:
{
while(ShowListBox.Items.Count != 0)
{
for(int i = 0; i < ShowListBox.Items.Count; i++)
{
ShowListBox.Items.Remove(ShowListBox.Items[i].ToString());
}
while (ShowListBox.Items.Count > 0)
{
ShowListBox.Items.RemoveAt(0);
}
}
}
在上面的代码中,所有数据都被删除(列表框中的文本、数字和任何符号)
当使用 Remove 函数来 RemoveAt 时,这会失败。