1) first define a person classClass person
{
Private int age;
Public int age
{
Get {return age ;}
Set {age = value ;}
}
Public Person (INT age)
{
This. Age = age;
}
}
2) define another personlist collection class, just inherit the list <person>Class personlist: List <person>
{
// Define the sorting method based on the comparison-Defined Signature
Public static int personsort (Person X, person y)
{
If (X. age> Y. Age)
{
Return-1;
}
If (X. age <Y. Age)
{
Return 1;
}
Return 0;
}
}
3) Portal function call
Static void main (string [] ARGs)
{
Personlist plist = new personlist ();
Plist. Add (new person (17 ));
Plist. Add (new person (21 ));
Plist. Add (new person (19 ));
Plist. Add (new person (12 ));
Console. writeline ("Default sequence :");
Foreach (person P in plist)
{
Console. writeline (P. Age );
}
// Define a strongly typed delegate
Comparison <person> sorter = new comparison <person> (personlist. personsort );
Plist. Sort (sorter );
Console. writeline ("Custom sorting :");
Foreach (person P in plist)
{
Console. writeline (P. Age );
}
Console. readkey ();
}
Plus: comparsion <t> This delegate type is used for sorting, and its signature isInt method (T objecta, t objectb)
Summary:
Defining a collection class and some methods in generic mode is indeed more convenient than inheriting from a collectionbase, where you do not need to manually write add () or remove () and so on. If you want the add () method of the Collection class to use an internal access modifier, collectionbase is recommended.