本文主要談的是委托相關運用。包括委托的簡單定義,使用,好處;以及委托和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;
}
}www.2cto.com
}
return list;
}
}
摘自:水木年華