using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 內部類使用接口實現排序 { class Person { private string _name; private int _age; public Person(string name, int age) { _name = name; _age = age; } public string Name { get { return _name; } } public int Age { get { return _age; } } private static AgeComparer _ageCom = null; //僅是一個靜態變量。 public static IComparer<Person> AgeCom { get { if (_ageCom == null) //當第一次訪問靜態屬性的時候,自動創建一個對象。 { _ageCom = new AgeComparer(); } return _ageCom; } } private class AgeComparer : IComparer<Person> { int IComparer<Person>.Compare(Person x, Person y) { return x._age.CompareTo(y._age); } } } class Program { static void Main(string[] args) { Person[] p1 = new Person[5]; p1[0] = new Person("王亮", 27); p1[1] = new Person("張明敏", 21); p1[2] = new Person("孫曉峰", 28); p1[3] = new Person("赫敏", 25); p1[4] = new Person("劉銘", 23); foreach (Person p in p1) { Console.WriteLine(p.Name + " " + p.Age.ToString()); } Console.WriteLine("將對年齡進行排序並打印結果:"); Array.Sort(p1, Person.AgeCom); foreach (Person p in p1) { Console.WriteLine(p.Name + " " + p.Age.ToString()); } Console.ReadKey(); } } }