标签:style blog io ar color os 使用 sp for
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(); } } }
标签:style blog io ar color os 使用 sp for
原文地址:http://www.cnblogs.com/han1982/p/4129645.html