为什么不Controls集合提供所有的IEnumerable的方法呢? [英] Why doesn't the Controls collection provide all of the IEnumerable methods?

查看:124
本文介绍了为什么不Controls集合提供所有的IEnumerable的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不肯定ASP.Net的ControlCollection中是如何工作的,所以也许有人可以提供一些线索上这对我来说。



我最近发现神奇的是扩展方法和LINQ。好吧,我很悲哀地发现,这不是有效的语法

 变种C = Controls.Where(X => 。x.ID ==有些ID)的SingleOrDefault(); 



不过从我可以告诉,控制确实实现了的IEnumerable 接口,它提供了这样的方法,那么怎么办?为什么不只是工作?我已经找到了体面的工作围绕此问题至少包括:

  VAR名单=(IEnumerable的<控制>)控制; 
VAR this_item = list.Where(X => x.ID ==有些ID)。的SingleOrDefault();


解决方案

没有,的IEnumerable 上没有了很多扩展方法:的IEnumerable< T> 一样。它们是两个独立的接口,虽然的IEnumerable< T> 扩展的IEnumerable


$ B。 $ b

转换的正常LINQ的方式是使用 演员LT; T> () OfType< T> () 扩展方法其中的的扩展非泛型接口:

 的IEnumerable<&文本框GT;文本框= Controls.OfType<&文本框GT;(); 
IEnumerable的<控制>控制= Controls.Cast<控制>();



这两者之间的区别是, OfType 会跳过这是需要的类型不属于任何物品; 铸造将抛出一个异常,而不是



一旦你引用泛型 IEnumerable的< T> 类型的LINQ方法其余全部都可以。


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();

解决方案

No, IEnumerable doesn't have many extension methods on it: IEnumerable<T> does. They are two separate interfaces, although IEnumerable<T> extends IEnumerable.

The normal LINQ ways of converting are to use the Cast<T>() and OfType<T>() extension methods which do extend the nongeneric interface:

IEnumerable<TextBox> textBoxes = Controls.OfType<TextBox>();
IEnumerable<Control> controls = Controls.Cast<Control>();

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.

这篇关于为什么不Controls集合提供所有的IEnumerable的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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