在.net framework中,数组和集合都实现了用于排序的方法sort(),数组通过调用Array.Sort(数组名)排序,集合通过调用 集合对象.Sort()方法排序。
默认的排序是使用升序排列,并且只能针对基本的数值类型排序,因为数值类型默认实现了对两个值比较的接口。但如果是引用类型需要排序,则此引用类型
需要实现IComparable接口,实现接口中的CompareTo()方法用于比较两个对象。
与比较和排序有关的接口有四个:非范型版本IComparable和IComparer,范型版本IComparable<T>和IComparer<T>
IComparable接口的主要目的是在需要比较和排序的类中实现CompareTo()方法,用于定义此类的2个对象比较的时候的默认的比较规则。
IComparer接口的主要目的是使某个继承此接口的类实现Comapre()方法,在此方法中定义两个对象的比较规则。此类就可以作为Sort()函数的参数,用于
在排序的时候作为比较和排序的规则。
例如:如果我们有一个学生类Student,有4个字段:int ID;Name;Score;如果有一个学生数组或学生集合,此集合需要排序。
则我们要做的工作为:
1.使Student能被比较和排序,就要实现IComparable接口,在CompareTo()方法中定义默认的排序规则,例如升序。
2.如果要实现降序,则我们需要定义一个类,此类实现IComparer接口,在Compare()中定义另外一种比较和排序的规则,例如降序。
3.调用Sort()方法实现排序,此方法可以不带参数,按默认规则排序,也可以把实现了IComparer的接口的类的对象作为参数,这样排序时将按照
另外一种规则排序。
下面示例演示了按升序或降序对一个Student类的数组或集合进行了排序:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { //同时实现了范型和非范型的IComparable public class Student:IComparable,IComparable<Student> { public int ID; public string Name; public int Score; public Student(int id, string name, int score) { this.ID = id; this.Name = name; this.Score = score; } public string Info() { return string.Format("学号:{0,-5}姓名:{1,-5}分数:{2}",ID,Name,Score); } int IComparable.CompareTo(object obj) { return this.Score.CompareTo((obj as Student).Score); } int IComparable<Student>.CompareTo(Student other) { return this.Score.CompareTo(other.Score); } } //实现了非范型的IComparer接口 public class ReverseCompareClass : IComparer { int IComparer.Compare(object x, object y) { return ((new CaseInsensitiveComparer()).Compare(y, x)); } } //实现了范型的IComparer接口 public class StuReverseCompareClass : IComparer<Student> { int IComparer<Student>.Compare(Student x, Student y) { return y.Score.CompareTo(x.Score); } } class Program { static void Main(string[] args) { ArrayList stu = new ArrayList(); //List<Student> stu = new List<Student>(); int i; Random r = new Random(); for (i = 0; i < 10; i++) { stu.Add( new Student(i,i.ToString(),r.Next(60,90))); } //如果使用非范型集合,我们就在sort()中使用非范型的比较类 stu.Sort(new ReverseCompareClass()); //如果使用范型集合,我们就在sort()中使用范型的比较类 //stu.Sort(new StuReverseCompareClass()); for (i = 0; i < 10; i++) { Console.WriteLine((stu[i] as Student).Info()); //Console.WriteLine(stu[i].Info()); } Console.Read(); } } }
使用范型的好处是:类型安全,效率高,因为不存在装箱和拆箱操作。