加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ListItemCollection上的隐式类型不可能使用foreach,但可能

发布时间:2020-12-15 21:41:41 所属栏目:百科 来源:网络整理
导读:ListBox控件具有类型为 ListItemCollection的Items属性. 我有点理解为什么我不能写 foreach (var item in ShipperListBox.Items){ if (item.Selected) count++;} 但反而必须写 foreach (ListItem item in ShipperListBox.Items){ if (item.Selected) count++
ListBox控件具有类型为 ListItemCollection的Items属性.

我有点理解为什么我不能写

foreach (var item in ShipperListBox.Items)
{
    if (item.Selected) count++;
}

但反而必须写

foreach (ListItem item in ShipperListBox.Items)
{
    if (item.Selected) count++;
}

它与实现IEnumerable而不是IEnumerable< ListItem>的ListItemCollection有关. (如this question所述).

但我没有得到的是为什么以下是没有问题的.

for (int i = 0; i < ListBox1.Items.Count; i++)
{
    if (ListBox1.Items[i].Selected) count++;
}

ListItemCollection的哪个部分使编译器清楚ListBox.Items [i]的类型是ListItem?

解决方法

因为ListItemCollection实现了一个返回ListItem的 indexer.

这与IEnumerable是分开的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读