I would like to share with you an example of a classic study of C # delegation. I hope it will be helpful to you.Code:
Bubblesorter. CS
Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Wrox. procsharp. Delegates
{
Delegate Bool Comparison ( Object X, Object Y );
Class Bubblesorter
{
Static Public Void Sort ( Object [] Sortarray, comparison comparer)
{
For ( Int I = 0 ; I < Sortarray. length; I ++ )
{
For ( Int J = I + 1 ; J < Sortarray. length; j ++ )
{
If (Comparer (sortarray [J], sortarray [I])
{
Object Temp = Sortarray [I];
Sortarray [I] = Sortarray [J];
Sortarray [J] = Temp;
}
}
}
}
}
}
Employee. CS
Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Wrox. procsharp. Delegates
{
Class Employee
{
Private String Name;
Private Decimal Salary;
Public Employee ( String Name, Decimal Salary)
{
This . Name = Name;
This . Salary = Salary;
}
Public Override String Tostring ()
{
Return String . Format ( " {0}, {1: c} " , Name, salary );
}
Public Static Bool Comparesalary ( Object X, Object Y)
{
Employee E1 = (Employee) X;
Employee E2 = (Employee) y;
Return (E1.salary < E2.salary );
}
}
}
Program. CS
Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Wrox. procsharp. Delegates
{
Class Program
{
Static Void Main ()
{
Employee [] employees =
{
New Employee ( " Bugs Bunny " , 20000 ),
New Employee ( " Elmer Fudd " , 10000 ),
New Employee ( " Daffy Duck " , 25000 ),
New Employee ( " Wiley coyote " ,( Decimal ) 1000000.38 ),
New Employee ( " Foghorn Leghorn " , 23000 ),
New Employee ( " Roadrunner' " , 50000 )};
// Comparison comp = employee. comparesalary; // Instantiate a delegate using the employee. comparesalary method.
Bubblesorter. Sort (employees, employee. comparesalary );
Foreach (VAR employee In Employees)
{
Console. writeline (employee );
}
Console. Readline ();
// For (INT I = 0; I <employees. length; I ++)
// Console. writeline (employees [I]. tostring ());
}
}
}