为什么我必须调用演员LT;>上的DataGridViewRow扩展方法? [英] Why do I have to call the Cast<> extension method on a DataGridViewRow?

查看:94
本文介绍了为什么我必须调用演员LT;>上的DataGridViewRow扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是行不通的。

var result = 
    from row in grid.Rows
    where (string) row.Cells["COLUMN_1"].Value == "Test"
    select row.Cells["COLUMN_2"].Value as int?;

但这。

var result = 
    from row in grid.Rows.Cast<DataGridViewRow>()
    where (string) row.Cells["COLUMN_1"].Value == "Test"
    select row.Cells["COLUMN_2"].Value as int?;

据我所知道的,DataGridViewRowCollection是DataGridViewRows的集合。那么,为什么我要每个成员转换为一个DataGridViewRow之前,我可以访问它的属性?

As far as I can tell, the DataGridViewRowCollection is a collection of DataGridViewRows. So why do I have to cast each member to a DataGridViewRow before I can access its properties?

是否有任何与该DataGridViewRowCollection实现非泛型的IEnumerable 而不是通用版本的事实的IEnumerable&LT;一个DataGridViewRow&GT; ?或者说,它显然是使用了的ArrayList 内部?这不是我造成任何实际问题,但我想更好地理解它。

Does it have anything to do with the fact that DataGridViewRowCollection implements the non-generic IEnumerable but not the generic version IEnumerable<DataGridViewRow>? Or that it apparently uses an ArrayList internally? It's not causing me any real problems, but I'd like to understand it better.

推荐答案

是的,这就是它将把这个接口正是因为。几乎在在LINQ工作的所有扩展方法的IEnumerable&LT; T&GT; ,而不是的IEnumerable 演员LT;&GT; 是缩小这种差距的一种方式 - OfType&LT;&GT; 另一个

Yes, it's exactly because of the interface it advertises. Almost all the extension methods in LINQ work on IEnumerable<T> rather than IEnumerable. Cast<> is one way of bridging that gap - OfType<> is another.

然而,有叫的更简单的方法演员LT; T&GT; - 只是明确键入范围变量:

However, there's a simpler way of calling Cast<T> - just explicitly type your range variable:

var result = 
    from DataGridViewRow row in grid.Rows
    where (string) row.Cells["COLUMN_1"].Value == "Test"
    select row.Cells["COLUMN_2"].Value as int?;

编译器开启到这一点完全一样的code作为你的第二个样本。

The compiler turns this into exactly the same code as your second sample.

这篇关于为什么我必须调用演员LT;&GT;上的DataGridViewRow扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆