I am interestend in the reason why the var keyword does not work properlyin a foreach-loop on the DataGridViewSelectedRowCollection.
ex1:
var selectedRows = MyDataGridView.SelectedRows;
foreach (var row in selectedRows)
{
var foo = row.DataBoundItem;
_bindingSource.Remove(foo);
}
ex1 the type of 'row' is object. Why is it not of type 'DataGridViewRow'
ex2 works perfectly:
var selectedRows = MyDataGridView.SelectedRows;
foreach (DataGridViewRow row in selectedRows)
{
var foo = row.DataBoundItem;
_bindingSource.Remove(foo);
}
also if I access the item of the collection directly it works:
var selectedRows = MyDataGridView.SelectedRows;
var foo = selectedRows[0];
var bar = foo.GetType().Name; // bar == DataGridViewRow
I am interested in the reason why this happens.
Thanks in advance
The DataGridView.SelectedRows Property returns a DataGridViewSelectedRowCollection . The type declaration for DataGridViewSelectedRowCollection class is:
public class DataGridViewSelectedRowCollection : BaseCollection,
IList, ICollection, IEnumerable
Notice that the class implements IEnumerable
, but not IEnumerable<DataGridViewRow>
. The IEnumerator.Current Property that is returned as the item of a foreach
loop is of type System.Object
. Therefore, the IDE/compiler is assigning var row
an object type and technically the type inference is working as specified.
The reason var foo = selectedRows[0];
works , is that the DataGridViewSelectedRowCollection.Item Property returned by the C# indexer is typed as a DataGridViewRow, so the type inference picks that up.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.