// 实现可比较接口 using System; class Salary : IComparable{ public Salary(int val){ this.val = val; } public int val { set; get; } override public string ToString() { return val.ToString(); } public int CompareTo(Salary salary) { return this.val.CompareTo(salary.val); } }
// 实现比较器 using System.Collections.Generic; class SalaryComparer : IComparer { public int Compare(Salary a, Salary b) { return a.CompareTo(b); } }
List ls = new List(); ls.Add(new Salary(3)); ls.Add(new Salary(2)); ls.Add(new Salary(1)); ls.Sort(new SalaryComparer()); foreach(Salary s in ls) { Debug.Log(s); // 1 2 3 }