刚复习了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);
}

输出排序后的数组:

Array类的Sort()方法

 

如果对数组使用定制的类,就必须实现IComparable接口。这个借口定义了一个方法CompareTo()。

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 }

相关文章: