为什么 var 在 DataGridViewSelectedRowCollectoin 上不起作用

Why does var not work on DataGridViewSelectedRowCollectoin

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

ex1:

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

ex1 'row' 的类型是对象。 为什么不是 '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

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

提前致谢

DataGridView.SelectedRows Property returns a DataGridViewSelectedRowCollection。 DataGridViewSelectedRowCollection class 的类型声明是:

public class DataGridViewSelectedRowCollection : BaseCollection, 
    IList, ICollection, IEnumerable

请注意 class 实现了 IEnumerable,而不是 IEnumerable<DataGridViewRow>。作为 foreach 循环的项返回的 IEnumerator.Current Property 的类型为 System.Object。因此,IDE/compiler 正在分配 var row 一个对象类型,从技术上讲,类型推断正在按指定工作。

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