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

956 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<T> (this IEnumerable<T> source, Action<T> 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 <T>(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<T> GetControls<T>(this Control control, Func<T, bool> 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<T>(c, filter))
 		yield return _t;
 	}
}

使用方法:

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


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

Add your comment

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

  1. lonkil CHINA Mozilla Firefox Windows 说:

    很强大的插件,Coder的福音。不过大段代码中,如果有Html/js有冲突,还需要手动处理。

  2. admin CHINA Google Chrome Windows 说:

    @lonkil
    哦,html/js还没试过……

  3. 不错,收藏了!!WP好友!

  4. 久酷 CHINA Mozilla Firefox Windows 说:

    有自己的小孩了啊,幸福,羡慕啊

  5. Cooldog CHINA Google Chrome Windows 说:

    @久酷
    谢谢,呵呵……

  6. zwwooooo CHINA Mozilla Firefox Ubuntu Linux 说:

    没接触过.net,一头雾水。哈,又一个已做爸爸的博主。

  7. 混乱羽翼 CHINA Internet Explorer Windows 说:

    哎呀…评论窗口为什么这么小…是不是错误了??还是本来就是酱紫

  8. Firm CHINA Google Chrome Windows 说:

    新年快乐,红包拿来

  9. 王家荣 AUSTRALIA Mozilla Firefox Windows 说:

    路过,支持一下,O(∩_∩)O~ 领教了,写的很专业。。


Leave a Reply

(Ctrl+Enter)