为什么 Controls 集合不提供所有 IEnumerable 方法?
我不确定 ASP.Net 的 ControlCollection 是如何工作的,所以也许有人可以为我阐明这一点。
我最近发现了扩展方法和 Linq 的神奇之处。好吧,我很遗憾地发现这不是有效的语法
var c=Controls.Where(x => x.ID=="Some ID").SingleOrDefault();
但是据我所知, Controls
确实实现了提供此类方法的 IEnumerable
接口,那么什么给了?为什么这不起作用?我至少为这个问题找到了一个不错的解决方法:
var list = (IEnumerable<Control>)Controls;
var this_item = list.Where(x => x.ID == "Some ID").SingleOrDefault();
I'm not for sure how the ControlCollection of ASP.Net works, so maybe someone can shed some light on this for me.
I recently discovered the magic that is extension methods and Linq. Well, I was very sad to find that this isn't valid syntax
var c=Controls.Where(x => x.ID=="Some ID").SingleOrDefault();
However from what I can tell, Controls
does implement the IEnumerable
interface which provides such methods, so what gives? Why doesn't that just work? I have found a decent work around for this issue at least:
var list = (IEnumerable<Control>)Controls;
var this_item = list.Where(x => x.ID == "Some ID").SingleOrDefault();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,
IEnumerable
上没有很多扩展方法:IEnumerable
有。尽管IEnumerable
扩展了IEnumerable
,但它们是两个独立的接口。正常的 LINQ 转换方法是使用
Cast()
和OfType()< /code>
扩展非泛型接口的扩展方法:
两者之间的区别在于
OfType
将跳过任何不属于必需项的项目类型;Cast
将抛出异常。一旦获得了对通用
IEnumerable
类型的引用,所有其余的 LINQ 方法都可用。No,
IEnumerable
doesn't have many extension methods on it:IEnumerable<T>
does. They are two separate interfaces, althoughIEnumerable<T>
extendsIEnumerable
.The normal LINQ ways of converting are to use the
Cast<T>()
andOfType<T>()
extension methods which do extend the nongeneric interface:The difference between the two is that
OfType
will just skip any items which aren't of the required type;Cast
will throw an exception instead.Once you've got references to the generic
IEnumerable<T>
type, all the rest of the LINQ methods are available.这只是因为
ControlCollection
类在泛型之前出现;因此它实现了IEnumerable
,但没有实现IEnumerable
。幸运的是,
IEnumerable
接口上确实存在一个 LINQ 扩展方法,允许您通过转换生成一个IEnumerable
:Cast
。这意味着您始终可以这样做:This is just because the
ControlCollection
class came around before generics; so it implementsIEnumerable
but notIEnumerable<Control>
.Fortunately, there does exist a LINQ extension method on the
IEnumerable
interface that allows you to generate anIEnumerable<T>
through casting:Cast<T>
. Which means you can always just do this:除了 Jon Skeet 和 Dan Tao 提供的答案之外,您还可以通过显式提供类型来使用查询表达式语法。
In addition to the answers provided by Jon Skeet and Dan Tao, you can use query expression syntax by explicitly providing the type.
Linq 使用通用集合。 ControlsCollection 实现
IEnumerable
而不是IEnumberable
如果您发现这不起作用
但是,这确实有效
您可以转换为通用
IEnumerable
或者访问一个扩展方法,如下所示:Linq utilized Generic Collections. ControlsCollection implements
IEnumerable
notIEnumberable<T>
If you notice this will not work
However, this does
You can either cast to Generic
IEnumerable<T>
or access an extension method that does, like so: