zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    复习列表
    20201009 day30 复习2:滑动窗口
    20201009 day30 复习1:扫描线
    20201007day29 模拟(九)
    20201006day28 模拟(八)
    20201005day27 模拟(七)
    20201004 day26 模拟(六)
    20201003day25 模拟(五)
    路由重分布(一)
    RIP路由协议(一)
  • 原文地址:https://www.cnblogs.com/han1982/p/4129645.html
Copyright © 2011-2022 走看看