c# - 如何将 SelectedListViewItemCollection 转换为 ListViewItemCollection

标签 c# winforms listview

我正在尝试编写一个简单的例程来处理 ListView 中的项目列表,并且能够处理所有项目或仅处理选定的项目。我希望这会起作用:

private void PurgeListOfStudies(ListView.ListViewItemCollection lvic)
{
    /// process items in the list...
}

然后这样调用它:

PurgeListOfStudies(myStudiesPageCurrent.ListView.Items);

或者这个

PurgeListOfStudies(myStudiesPageCurrent.ListView.SelectedItems);

但是,这两个列表具有不同且不相关的类型,ListViewItemCollectionSelectedListViewItemCollection分别。

我尝试将参数类型更改为 object , ICollection<ListViewItem>和其他几件事。但是由于类型似乎完全不相关,所以无论是在编译时还是在运行时,在转换过程中,一切都会失败。

这一切对我来说似乎很奇怪,因为它们在现实中显然是同一类型(ListViewItem s 的列表)。

我是不是漏掉了什么?

最佳答案

使用 MSDN 文档。

如您所见,两个类都实现了接口(interface):IList , ICollection , 和 IEnumerable .您应该能够将其中任何一个用作通用接口(interface)。

请注意,这些不是通用版本(即 IEnumerable))。您必须枚举集合并手动将它们转换为所需的对象类型。

private void PurgeListOfStudies(IEnumerable items)
{
    foreach(MyType currentItem in items) //implicit casting to desired type
    {
        // process current item in the list...
    }
}

关于c# - 如何将 SelectedListViewItemCollection 转换为 ListViewItemCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565730/

相关文章:

c# - 尝试以编程方式创建和打开新的 Outlook 电子邮件

安卓。在 listView 中搜索

android - listview 和 recyclerview 不会用计数包装内容

c# - LINQ to Entities 多重连接

c# - Excel 到 SQL。批量复制的替代方案?

c# - 从大字符串中提取数据

javascript - winjs中水平 ListView 的左右导航

c# - EnableCrossAppRedirects - 跨域功能记录在哪里?

c# - SHGetKnownFolderPath/Environment.GetFolderPath() 返回公共(public)文档的错误值

c# - 如何处理此类问题 UnauthorizedAccessException Was handli Error?