【问题标题】:Why does var not work on DataGridViewSelectedRowCollectoin为什么 var 在 DataGridViewSelectedRowCollectoin 上不起作用
【发布时间】:2017-08-03 08:18:31
【问题描述】:

我对 var 关键字在 DataGridViewSelectedRowCollection 上的 foreach 循环中无法正常工作的原因很感兴趣。

ex1:

var selectedRows = MyDataGridView.SelectedRows;
foreach (var row in selectedRows)
        { 
            var foo = row.DataBoundItem;
            _bindingSource.Remove(foo);
        }

ex1 “行”的类型是对象。 为什么它不是'DataGridViewRow'类型

ex2 完美运行:

var selectedRows = MyDataGridView.SelectedRows;
foreach (DataGridViewRow row in selectedRows)
        { 
            var foo = row.DataBoundItem;
            _bindingSource.Remove(foo);
        }

如果我直接访问集合的项目,它也可以工作:

var selectedRows = MyDataGridView.SelectedRows;
var foo = selectedRows[0];
var bar = foo.GetType().Name; // bar == DataGridViewRow

我对发生这种情况的原因很感兴趣。

提前致谢

【问题讨论】:

  • 你试过在ex2中做selectedRows[0].DataBoundItem;吗?因为它不是一个“公平”的比较 atm :)

标签: c# winforms collections var


【解决方案1】:

DataGridView.SelectedRows Property 返回一个DataGridViewSelectedRowCollection。 DataGridViewSelectedRowCollection 类的类型声明为:

public class DataGridViewSelectedRowCollection : BaseCollection, 
    IList, ICollection, IEnumerable

请注意,该类实现了IEnumerable,但没有实现IEnumerable<DataGridViewRow>。作为foreach 循环的项返回的IEnumerator.Current PropertySystem.Object 类型。因此,IDE/编译器正在为 var row 分配一个对象类型,从技术上讲,类型推断正在按规定工作。

var foo = selectedRows[0];有效的原因是 C# 索引器返回的 DataGridViewSelectedRowCollection.Item Property 被键入为 DataGridViewRow,因此类型推断会选择它。

【讨论】:

  • 作为解决方法,如果您想要循环选定的行,您可以将集合转换为 DataGridViewRow - foreach(var row in dataGridView.SelectedRows.Cast<DataGridViewRow>()) ... 的集合
猜你喜欢
  • 2020-02-28
  • 2013-07-15
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 2012-04-27
  • 2023-01-26
  • 2015-10-19
  • 2018-02-01
相关资源
最近更新 更多