C# 列表框中的 Foreach 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2260852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreach statement in listbox
提问by Crazyd22
I have a problem with a foreach statement in my project. So far I have the code:
我的项目中的 foreach 语句有问题。到目前为止,我有代码:
foreach(object i in listboxFiles.Items)
{
if (i == ".ftpquota")
{
listboxFiles.Items.Remove(i);
}
if (i == ".")
{
listboxFiles.Items.Remove(i);
}
if (i == "..")
{
listboxFiles.Items.Remove(i);
}
}
I have this in a 1 second timer. It gets the item name all right, but when it gets to the if
statements it says that they do not match, but they do?
我有一个 1 秒的计时器。它可以正确获取项目名称,但是当它到达if
语句时,它说它们不匹配,但是它们匹配吗?
采纳答案by Konrad Rudolph
First thing, you are changing a collection whileiterating over it. This cannot work, so your code is fundamentally broken.
首先,您在迭代时更改集合。这行不通,所以你的代码从根本上被破坏了。
There are several ways to fix this; the simplest in your case would be to copy the items collection, iterating over the copy and changing (= removing from) the original:
有几种方法可以解决这个问题;在您的情况下,最简单的方法是复制项目集合,迭代副本并更改(= 删除)原始内容:
var items = new System.Collections.ArrayList(listboxFiles.Items);
foreach (var item in items) {
if (item.Equals("."))
listboxFiles.Items.remove(item);
…
}
Secondly, you are comparing an object
to a string
, hence the ==
operator does reference equality checking rather than testing for string equality. Either use Equals
or do an appropriate cast.
其次,您将 anobject
与 a进行比较string
,因此==
运算符会进行引用相等性检查,而不是测试字符串相等性。使用Equals
或进行适当的演员表。
回答by Adam Ralph
The equality check is not working because you should cast to string first and do an appropriate string comparison.
相等检查不起作用,因为您应该首先转换为字符串并进行适当的字符串比较。
e.g.
例如
if (string.Equals((string)i, ".ftpquota", StringComparison.Ordinal))
If you remove items from a collection of items whilst iterating through the collection, you may well run into trouble. One way to get around this problem is to start with the last item and count backwards, thus any removals you do will not affect the remaining items of the collection, e.g.
如果在迭代集合时从项目集合中删除项目,则很可能会遇到麻烦。解决这个问题的一种方法是从最后一个项目开始并倒数,因此您所做的任何删除都不会影响集合中的剩余项目,例如
for(var i = listboxFiles.Items.Count - 1; i >= 0; --i)
{
var item = listboxFiles[i];
if (...)
{
listboxFiles.Items.RemoveAt(i);
}
}