C # delegated Learning (2)

Source: Internet
Author: User

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 ());
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.