class person :IComparable<person>
{ public person(string name, string sex) { this.name = name; this.sex = sex; } public string name{set;get;} public string sex {set;get; }public int CompareTo(person other)
{ if (other == null) throw new ArgumentNullException("other"); int result = this.name.CompareTo(other.name); if (result == 0) { result = this.sex.CompareTo(other.sex); } return result; }public override string ToString()
{ return name + ":" + sex; } }
调用
person[] p = { new person("小明", "女"), new person("明红", "男"), new person("小明", "男") };
Array.Sort(p); foreach (var item in p) { Console.WriteLine(item.ToString()); }或者
IEnumerator enumerator = p.GetEnumerator();
while (enumerator.MoveNext()) { person p9 = (person)enumerator.Current; Console.WriteLine(p9.ToString()); }
System.String和System.Int32实现IComparable接口,所以Array只能对他们两进行排序
而如果数组中的元素是类的话,就要重写CompareTo(person other)方法