调用LIST的Sort的时候会调用IComparer的默认实现,quicksort会调用每个元素的CompareTo的IComparable实现
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ComparerTest{ class Employee : IComparable{ private int empID; private int yearOfSvc = 1; public Employee(int empID) { this.empID = empID; } public Employee(int empID, int yearOfSvc) { this.empID = empID; this.yearOfSvc = yearOfSvc; } public override string ToString() { return "ID: " + empID.ToString() + " yearOfSvc: " + yearOfSvc.ToString(); } public bool Equals(Employee other) { if (this.empID == other.empID) { return true; } else { return false; } } //获取Comparer对象的静态方法 public static EmployeeComparer GetComparer() { return new Employee.EmployeeComparer(); } //比较委托回Employee //Employee使用整形的默认 //CompareTo方法 public int CompareTo(Employee rhs) { return this.empID.CompareTo(rhs.empID); } //自定义Comparer要调用的特殊表现 public int CompareTo(Employee rhs, Employee.EmployeeComparer.ComparisonType whichComparision) { switch (whichComparision) { case Employee.EmployeeComparer.ComparisonType.EmpID: return this.empID.CompareTo(rhs.empID); case Employee.EmployeeComparer.ComparisonType.Yrs: return this.yearOfSvc.CompareTo(rhs.yearOfSvc); } return 0; } //实现IComparer的内嵌类 public class EmployeeComparer : IComparer { private Employee.EmployeeComparer.ComparisonType whichComparision; public enum ComparisonType { EmpID, Yrs }; public bool Equals(Employee lhs, Employee rhs) { return this.Compare(lhs, rhs) == 0; } //让Empolyee对象自己比较 public int Compare(Employee lhs, Employee rhs) { return lhs.CompareTo(rhs, WhichComparison); } public int GetHashCode(Employee e) { return e.GetHashCode(); } public Employee.EmployeeComparer.ComparisonType WhichComparison { set { whichComparision = value; } get { return whichComparision; } } } } class Program { static void Main(string[] args) { List empArray = new List (); Random ra = new Random(); for (int i = 0; i < 5; i++) { empArray.Add(new Employee(ra.Next(10)+100,ra.Next(20))); } for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0}",empArray[i].ToString()); } Console.WriteLine(); Console.WriteLine(); Employee.EmployeeComparer c = Employee.GetComparer(); c.WhichComparison = Employee.EmployeeComparer.ComparisonType.EmpID; empArray.Sort(c); for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0}", empArray[i].ToString()); } Console.WriteLine(); Console.WriteLine(); Employee.EmployeeComparer c2 = Employee.GetComparer(); c.WhichComparison = Employee.EmployeeComparer.ComparisonType.Yrs; empArray.Sort(c2); for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0}", empArray[i].ToString()); } Console.ReadLine(); } }}