[置顶]常用扩展方法收集&整理(置顶-不断更新)

1,051 views 十一月 14, 09 by Timothy

扩展方法,是.NET 3.5中引入的新特性,在《扩展方法使用小结中》,我有具体的介绍。合理的使用扩展方法,能节约不少的代码量,甚至能在开发中给我们带来意想不到的效果,让代码更加的简洁、易懂。其实,网上早就有了不少的大牛写的各种出色的扩展方法,以至于我有了整理一个扩展方法库的想法,把一些实用、优秀的扩展方法收集起来,一来为资源共享,二来也是为了应用在以后的项目代码中,提高开发效率。

1.Foreach方法
首先上场的是Foreach,在使用Linq的时候,太容易派上用场了。比如,在使用Linq to Sql查询后,我们常常需要遍历结果,然后输出,代码如下:

?View Code CSHARP
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,可以节省不少的力气了:

?View Code CSHARP
1
2
DataClassDataContext ctx = new DataClassDataContext();
ctx.Products.Where(p => p.ProductID >= 10).ForEach(p => Console.WriteLine(p.ProductName));

Foreach代码如下:

?View Code CSHARP
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方法
判断某个类型的变量是否在一个序列中

?View Code CSHARP
1
2
3
4
5
6
string [] names = new string[] {"Andy", "Timothy", "Ben", "Rex", "Ven", "Ken"};
 
if(names.Contains("Timothy"))
{
    Console.WriteLine("Found!");
}

使用In方法:

?View Code CSHARP
1
2
3
4
if ("Timothy".In("Andy", "Timothy", "Ben", "Rex", "Ven", "Ken"))
{
    Console.WriteLine("Found!");
}

In方法代码如下:

?View Code CSHARP
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)

?View Code CSHARP
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;
 	}
}

使用方法:

?View Code CSHARP
1
2
this.GetControls<button>(null).ForEach(b => b.Enabled = false);  //禁用界面上所有Button控件
</button>

分享到:

声明: 此Blog中的文章和随笔仅代表作者在某一特定时间内的观点和结论,对其完全的正确不做任何担保或假设
本站文章均采用 知识共享署名-相同方式共享3.0 协议进行授权,除非注明,本站文章均为原创,转载请注明转自 Timothy's Space 并应以链接形式标明本文地址!

你可能也对下列文章感兴趣


Add your comment

38 Responses to "[置顶]常用扩展方法收集&整理(置顶-不断更新)"

  1. 无机防火卷帘 CHINA Internet Explorer Windows 说道:

    路过。。学习了。。 呵呵

  2. 元胜 CHINA Internet Explorer Windows 说道:

    专业,外行,热闹

  3. zwwooooo CHINA Mozilla Firefox Windows 说道:

    要更新了哦,很久了

  4. OceanBan CHINA Mozilla Firefox Ubuntu Linux 说道:

    报告:我的1024*768的分辨率页面无法显示完全。

  5. 阿修 CHINA Google Chrome Windows 说道:

    .net?当初看了看,头大啊!~

  6. 解梦 CHINA Mozilla Firefox Windows 说道:

    整理的太好了,很实用的

  7. littlebear CANADA 说道:

    谢谢, 顶一下~

  8. ikeeptrying AUSTRALIA Google Chrome Windows 说道:

    第一次来博主这~
    留个脚印

  9. 时尚妈妈 CHINA Internet Explorer Windows 说道:

    无意间来到这里,留下一点痕迹吧~

  10. C瓜哥 CHINA Mozilla Firefox Windows 说道:

    上面几个用IE的,是来打广告的!可惜反垃圾评论插件拦不住~


Leave a Reply

 您已输入0

(Ctrl+Enter)