c# 內部類使用接口IComparer實現排序


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();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM