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

1,004 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>


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


Add your comment

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

  1. lonkil CHINA Google Chrome Windows 说:

    原来,你这也存在get recent comment截断乱码,我换了主机,也出现在这个问题。

  2. 卢松松 CHINA Mozilla Firefox Windows 说:

    这个东西干嘛用的

  3. ptubuntu CHINA Google Chrome Linux 说:

    看不懂.晕晕了.路过了.

  4. 脚印 CHINA Google Chrome Windows 说:

    不错。收藏了。也欢迎您来 小博交流: http://www.jiao-yin.com


Leave a Reply

(Ctrl+Enter)