Lambda表达式可以在使用代理和匿名代理的地方
1、命名函数
2、匿名函数
3、Lambda表达式
三种方式的比较
命名函数虽然简短,但是而外还要定义处理函数,优点是可以重用
1、命名函数
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 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);
}
}
{
public static bool IsOdd(int i)
{
return ((i & 1) == 1);
}
}
using System.Collections;
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums = Common.FilterArrayOfInts(nums, Application.IsOdd);
foreach (int i in oddNums)
Console.WriteLine(i);
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums = Common.FilterArrayOfInts(nums, Application.IsOdd);
foreach (int i in oddNums)
Console.WriteLine(i);
2、匿名函数
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums =
Common.FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
foreach (int i in oddNums)
Console.WriteLine(i);
int[] oddNums =
Common.FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
foreach (int i in oddNums)
Console.WriteLine(i);
3、Lambda表达式
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums = Common.FilterArrayOfInts(nums, i => ((i & 1) == 1));
foreach (int i in oddNums)
Console.WriteLine(i);
int[] oddNums = Common.FilterArrayOfInts(nums, i => ((i & 1) == 1));
foreach (int i in oddNums)
Console.WriteLine(i);
三种方式的比较
int[] oddNums = // using named method
Common.FilterArrayOfInts(nums, Application.IsOdd);
int[] oddNums = // using anonymous method
Common.FilterArrayOfInts(nums, delegate(int i){return((i & 1) == 1);});
int[] oddNums = // using lambda expression
Common.FilterArrayOfInts(nums, i => ((i & 1) == 1));
Common.FilterArrayOfInts(nums, Application.IsOdd);
int[] oddNums = // using anonymous method
Common.FilterArrayOfInts(nums, delegate(int i){return((i & 1) == 1);});
int[] oddNums = // using lambda expression
Common.FilterArrayOfInts(nums, i => ((i & 1) == 1));
命名函数虽然简短,但是而外还要定义处理函数,优点是可以重用