This article focuses on the application of delegation. Including simple definition, use, benefits of delegation, and relationship between delegation and Lambda. All knowledge points are simplified to heuristic comments, which are not difficult to understand and hope to help you.
/// <Summary>
/// Delegate makes the Sorting Code more elegant (easy to expand and easy to maintain)
/// Knowledge points included in this article:
/// 1. Delegate Definition
/// 2. Delegate benefits
/// 3. Lamda (including statements Lamda and expressions Lambda)
/// 4. Relationship between Lambda and Delegation
/// </Summary>
Class Program
{
// Define embedded Delegate (the Delegate is essentially a class; the compiler inherits from System. Delegate by default)
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 ()));
/// Real-name delegate passing Parameters
// Int [] afterSortList = BubbleSort (beforeSortList, Asb );
// Int [] afterSortList = BubbleSort (beforeSortList, Desc );
/// Parameters passed by anonymous methods
// Int [] afterSortList = BubbleSort (beforeSortList, delegate (int first, int second) {return first> second ;});
// Int [] afterSortList = BubbleSort (beforeSortList, delegate (int first, int second) {return first <second ;});
/// Statement Lambda passing parameters (Lambda is a simplified syntax for anonymous methods)
Int [] afterSortList = BubbleSort (beforeSortList, (first, second) =>{ return first> second ;});
Console. WriteLine (string. Join (",", afterSortList. ToArray ()));
}
Bytes --------------------------------------------------------------------------------------------------------------------------
// Use delegation to achieve --> open to expansion
// Ascending
// Public static bool Asb (int first, int second)
//{
// Return first> second;
//}
// Descending order
Public static bool Desc (int first, int second)
{
Return first <second;
}
// Sort letters
// Other scalable sorting ......
Bytes --------------------------------------------------------------------------------------------------------------------------
// Bubble sort
// Use the delegate to achieve --> the modification is closed.
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;
}
}
From: Shui Mu Nian