c#扩展方法奇思妙用高级篇一:改进Scottgu的"In"扩展2010-04-23 博客园 鹤冲天先看下ScottGu对In的扩展:

调用示例1:

调用示例2:

原文地址:New "Orcas" Language Feature: Extension Methods(http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx)很多介绍扩展方法的也大都使用"In"作为例子,但很少有人再深入想一步。个人感觉这个In扩展的不够彻底,试看如下代码:
public static void Example1()
{
bool b1 = 1.In(new int[] { 1, 2, 3, 4, 5 });
bool b2 = "Tom".In(new string[] { "Bob", "Kitty", "Tom" });
}
//ScottGu In扩展
public static bool In(this object o, IEnumerable c)
{
foreach (object i in c)
{
if (i.Equals(o)) return true;
}
return false;
}
每次使用 In 时都要声明一个数组(或集合),有点麻烦,如果像下面这个样子调用应该比较简单一些:
public static void Example2()
{
bool b1 = 1.In(1, 2, 3, 4, 5);
bool b2 = 1.In(1, 2, 3, 4, 5, 5, 7, 8);
bool b3 = "Tom".In("Bob", "Kitty", "Tom");
bool b4 = "Tom".In("Bob", "Kitty", "Tom", "Jim");
}
感觉如何,是否有点类似SQL中的In?