通过列表视图访问并访问子项目?

soo*_*ise 22 c# foreach listview winforms

我在使用带有WinForm ListView控件的foreach语句时遇到了困难.以下两个代码块演示了我正在尝试做的事情.它适用于for循环,但不适用于foreach.

foreach(var item in listView.Items){
    item. <-Can't access any of the subitems of this item
}
Run Code Online (Sandbox Code Playgroud)

VS

for(int i=0;i<listView.Items.Count;i++){
    listView.Items[i].Subitems[1] <- Here I can access the sub items
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用foreach循环,以便我可以更轻松地从ListView中删除项目.

Bol*_*ock 51

您需要指定类型:

foreach(ListViewItem item in listView.Items){
Run Code Online (Sandbox Code Playgroud)

回答你的意见:

这是因为大多数控件的项集合实现非泛型ICollection(和IEnumerable),看到这个MSDN项对于ListViewItemCollection例如.由于它没有实现泛型ICollection<T>或者IEnumerable<T>,编译器无法通过查看集合本身来猜测项目的类型,因此您必须告诉它它们是类型ListViewItem而不是使用var.