c#中类实现了IComparabe 接口后可实现对此类集合排序等相关操作
class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); Person[] pserons=new Person[3]; pserons[0]=new Person{}; pserons[1]=new Person{age=5}; pserons[2]=new Person{age=2}; Console.WriteLine(" 排序前 "); foreach(var item in pserons) { Console.WriteLine("compareResult "+item.age+" Press any key to continue . . . "); } Array.Sort(pserons); Console.WriteLine(" 排序后 "); foreach(var item in pserons) { Console.WriteLine("compareResult "+item.age+" Press any key to continue . . . "); } Console.ReadKey(true); } } //实现比较接口 public class Person:IComparable { public int age=0; #region IComparable implementation int IComparable.CompareTo(object obj) { var person=obj as Person; if(person!=null) { if(this.age>person.age) return 1; if(this.age<person.age) return -1; return 0; } else { throw new NotImplementedException("is not a person"); } } #endregion }
结果图如下,实现了年龄的排序,还可以实现对多个字段的排序这里不详写了: