Array类的Sort()方法
刚复习了Array类的sort()方法, 这里列举几个常用的,和大家一起分享。
Array类实现了数组中元素的冒泡排序。Sort()方法要求数组中的元素实现IComparable接口。如System.Int32
和System.String实现了IComparable接口,所以下面的数组可以使用Array.Sort()。
string[] names = { "Lili", "Heicer", "Lucy" };
Array.Sort(names);
foreach (string n in names) {
Console.WriteLine(n);
}
输出排序后的数组:
如果对数组使用定制的类,就必须实现IComparable接口。这个借口定义了一个方法CompareTo()。<喎?http://www.zzzyk.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxkaXYgY2xhc3M9"cnblogs_code" onclick="cnblogs_code_show(139a6c7f-4e03-446d-a73a-c588771ba92e)">Person类
1 public class Person : IComparable {
2 public Person() { }
3 public Person(string name, string sex) {
4 this.Name = name;
5 this.Sex = sex;
6 }
7 public string Name;
8 public string Sex;
9
10 public override string ToString() {
11 return this.Name + " " + this.Sex;
12 }
13 #region IComparable 成员
14 public int CompareTo(object obj) {
15 Person p = obj as Person;
16 if (p == null) {
17 throw new NotImplementedException();
18 }
19 return this.Name.CompareTo(p.Name);
20 }
21 #endregion
22 }