委托,匿名方法,Lambda表达式使用实例
问题描述
排序函数中需要指定升序或降序排列,如果只是简单使用一个
Flag
进行标记的话,需要在排序函数中使用if else
进行判断。
class SimpleSort
{
public enum SortType
{
Ascending,
Descending
}
void BubleSort(int[] items, SortType sortOrder)
{
for (i = items.Length - 1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
bool swap = false;
switch (sortOrder)
{
case SortType.Ascending :
swap = items[j - 1] > items[j];
break;
case SortType.Descending :
swap = items[j - 1] < items[j];
break;
}
if (swap)
{
temp = items[j - 1];
items[j - 1] = items[j];
items[j] = temp;
}
}
}
}
}
使用委托改进排序方法
public delegate bool ComparisonHandler (int first, int second);
class DelegateSample
{
public static void BubbleSort(int[] items, ComparisonHandler comparisonMethod)
{
int i;
int j;
int temp;
if(comparisonMethod == null)
{
throw new ArgumentNullException("comparisonMethod");
}
if(items==null)
return;
for (i = items.Length - 1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (comparisonMethod(items[j - 1], items[j]))
{
temp = items[j - 1];
items[j - 1] = items[j];
items[j] = temp;
}
}
}
}
public static bool GreaterThan(int first, int second)
{
return first > second;
}
static void Main()
{
int i;
int[] items = new int[5];
for (i=0; i < items.Length; i++)
{
Console.Write("Enter an integer: ");
items[i] = int.Parse(Console.ReadLine());
}
BubbleSort(items, GreaterThan);
for (int i = 0; i < items.Length; i++)
Console.WriteLine(items[i]);
}
}
使用委托
class DelegateSort
{
public static bool GreaterThan(int first, int second)
{
return first > second;
}
static void Main()
{
int i;
int[] items = new int[5];
for (i=0; i < items.Length; i++)
{
Console.Write("Enter an integer: ");
items[i] = int.Parse(Console.ReadLine());
}
BubbleSort(items, GreaterThan);
for (int i = 0; i < items.Length; i++)
Console.WriteLine(items[i]);
}
}
匿名方法
BubbleSort(items,
delegate(int first, int second) => { return first > second; }
);
Lambda表达式
BubbleSort(items,
(int first, int second) => { return first > second; }
);
BubbleSort(items, (first, second) => first > second);
参考
1.《C#本质论 第六版》