[置顶]常用扩展方法收集&整理(置顶-不断更新)
1,051 views 十一月 14, 09 by Timothy扩展方法,是.NET 3.5中引入的新特性,在《扩展方法使用小结中》,我有具体的介绍。合理的使用扩展方法,能节约不少的代码量,甚至能在开发中给我们带来意想不到的效果,让代码更加的简洁、易懂。其实,网上早就有了不少的大牛写的各种出色的扩展方法,以至于我有了整理一个扩展方法库的想法,把一些实用、优秀的扩展方法收集起来,一来为资源共享,二来也是为了应用在以后的项目代码中,提高开发效率。
1.Foreach方法
首先上场的是Foreach,在使用Linq的时候,太容易派上用场了。比如,在使用Linq to Sql查询后,我们常常需要遍历结果,然后输出,代码如下:
1 2 3 4 5 6 7 | DataClassDataContext ctx = new DataClassDataContext(); var result = ctx.Products.Where(p => p.ProductID >= 10); foreach (var product in result) { Console.WriteLine(product.ProductName); } |
自从有了Foreach,可以节省不少的力气了:
1 2 | DataClassDataContext ctx = new DataClassDataContext(); ctx.Products.Where(p => p.ProductID >= 10).ForEach(p => Console.WriteLine(p.ProductName)); |
Foreach代码如下:
1 2 3 4 5 6 7 | public static void ForEach (this IEnumerable source, Action action) { foreach(var item in source) { action(item); } } |
2.In方法
判断某个类型的变量是否在一个序列中
1 2 3 4 5 6 | string [] names = new string[] {"Andy", "Timothy", "Ben", "Rex", "Ven", "Ken"}; if(names.Contains("Timothy")) { Console.WriteLine("Found!"); } |
使用In方法:
1 2 3 4 | if ("Timothy".In("Andy", "Timothy", "Ben", "Rex", "Ven", "Ken")) { Console.WriteLine("Found!"); } |
In方法代码如下:
1 2 3 4 | public static bool (this T t, params T[] c) { return c.Contains(t); } |
3.WinForm下的控件选择器(摘自 博客园-鹤冲天 的博客 http://www.cnblogs.com/ldp615/archive/2009/11/08/1598596.html)
1 2 3 4 5 6 7 8 9 10 11 12 | public static IEnumerable GetControls(this Control control, Func filter) where T : Control { foreach (Control c in control.Controls) { if (c is T&&(filter == null||filter(c as T))) { yield return c as T; } foreach (T _t in GetControls(c, filter)) yield return _t; } } |
使用方法:
1 2 | this.GetControls<button>(null).ForEach(b => b.Enabled = false); //禁用界面上所有Button控件 </button> |
声明: 此Blog中的文章和随笔仅代表作者在某一特定时间内的观点和结论,对其完全的正确不做任何担保或假设
本站文章均采用 知识共享署名-相同方式共享3.0 协议进行授权,除非注明,本站文章均为原创,转载请注明转自 Timothy's Space 并应以链接形式标明本文地址!
路过。。学习了。。 呵呵
专业,外行,热闹
@元胜: 欢迎交流
要更新了哦,很久了
@zwwooooo: 最近文囧得厉害……
报告:我的1024*768的分辨率页面无法显示完全。
@OCEANBAN: 这我知道,当初为了把页面尺寸改大,牺牲了小分辨率浏览的美观。 建议使用1024以上分辨率浏览
.net?当初看了看,头大啊!~
@阿修: 呵呵,其实也不难……
整理的太好了,很实用的
谢谢, 顶一下~
@littlebear: 惭愧,很久没更新了……
第一次来博主这~
留个脚印
@ikeeptrying: welcome!
无意间来到这里,留下一点痕迹吧~
上面几个用IE的,是来打广告的!可惜反垃圾评论插件拦不住~
@C瓜哥: 人肉spam……