代码改变世界

Lambda

2011-02-15 23:41  YZGJTSJT  阅读(381)  评论(0编辑  收藏  举报

在Adam Freeman and Joseph C. Rattz, Jr.的著作《Pro LINQ》一书中,关于Lambda的讲解很精辟,把Lambda的演化讲解的很透彻。

     public class Common
     {
         
public delegate bool IntFilter(int i);
         
public static int[] FilterArrayOfInts(int[] ints, IntFilter filter)
         {
             ArrayList aList 
= new ArrayList();
             
foreach (int i in ints)
             {
                 
if (filter(i))
                 {
                     aList.Add(i);
                 }
             }
             
return ((int[])aList.ToArray(typeof(int)));
         }
     }

 

     public class Application
     {
         
public static bool IsOdd(int i)
         {
              
return ((i & 1== 1);
         }
     }
在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。
    int[] nums = { 12345678910 };

    
int[] oddNums = Common.FilterArrayOfInts(nums, Application.IsOdd);

    
foreach (int i in oddNums)

        Console.WriteLine(i);

    Here are the results:

    
/* 1 3 5 7 9 */
C# 2.0 引入了匿名方法。
    int[] nums = { 12345678910 };

    
int[] oddNums =Common.FilterArrayOfInts(

         nums, 
delegate(int i) { return ((i & 1== 1); });

    
foreach (int i in oddNums)

        Console.WriteLine(i);

    Here are the results:

    
/* 1 3 5 7 9 */
而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式。
    int[] nums = { 12345678910 };

    
int[] oddNums = Common.FilterArrayOfInts(nums, i => ((i & 1== 1));

    
foreach (int i in oddNums) 

        Console.WriteLine(i);

    Here are the results:

    
/* 1 3 5 7 9 */
三种书写方式对比 
    // using named method
    public static bool IsOdd(int i)
    {
        
return ((i & 1== 1);
    }
    Common.FilterArrayOfInts(nums, Application.IsOdd);
    
// using anonymous method
    Common.FilterArrayOfInts(nums, delegate(int i) { return ((i & 1== 1); });
    
// using lambda expression
    Common.FilterArrayOfInts(nums, i => ((i & 1== 1));

 

最后作者也指出,无论你是使用命名方法、匿名方法,或lambda表达式,根据实际项目需要,选择适合的。三者没有孰优孰劣。