本文主要谈的是委托相关运用。包括委托的简单定义,使用,好处;以及委托和Lambda的关系。所有知识点都简化为启发式的注释,应该不难理解,希望对你有帮助。
/// <summary>
/// 委托让排序代码更加优雅(易扩展,易维护)
/// 本文包含知识点:
/// 1.委托定义
/// 2.委托的好处
/// 3.Lamda(包括语句Lamda和表达式Lambda)
/// 4.Lambda和委托的关系
/// </summary>
class Program
{
//定义内嵌委托(委托本质是一个类;编译器默认为继承自System.Delegate)
public delegate bool ComparerionHandler(int first, int second);
static void Main(string[] args)
{
int[] beforeSortList = new int[3] { 1, 3, 2 };
Console.WriteLine(string.Join(",", beforeSortList.ToArray()));
///实名委托传递参数
//int[] afterSortList = BubbleSort(beforeSortList, Asb);
//int[] afterSortList = BubbleSort(beforeSortList, Desc);
///匿名方法传递参数
//int[] afterSortList = BubbleSort(beforeSortList, delegate(int first, int second) { return first > second; });
//int[] afterSortList = BubbleSort(beforeSortList, delegate(int first, int second) { return first < second; });
///语句Lambda传递参数(Lambda是匿名方法的简化语法)
int[] afterSortList = BubbleSort(beforeSortList, (first, second)=>{ return first > second; });
Console.WriteLine(string.Join(",", afterSortList.ToArray()));
}
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//利用委托达到-->对扩展是开放的
//升序
//public static bool Asb(int first, int second)
//{
// return first > second;
//}
//降序
public static bool Desc(int first, int second)
{
return first < second;
}
//字母排序
//可扩展的其他排序……
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//冒泡排序
//利用委托达到-->对修改是封闭的
public static int[] BubbleSort(int[] list, ComparerionHandler compareion)
{
int temp;
for (int i = list.Length - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (compareion(list[j - 1], list[j]))
{
temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
}
}
}
return list;
}
}