欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深入IComparable与IComparer的排序实例详解

程序员文章站 2024-02-14 10:26:58
如下所示:复制代码 代码如下:using system;using system.collections.generic;using system.text;using s...
如下所示:
复制代码 代码如下:

using system;
using system.collections.generic;
using system.text;
using system.collections;
namespace hgoapp
{
    class comparer
    {
        static void main()
        {
            employee[] employees = new employee[5];

            employees[0] = new employee("张三", 2800);
            employees[1] = new employee("李四", 1800);
            employees[2] = new employee("王五", 5800);
            employees[3] = new employee("马六", 12800);
            employees[4] = new employee("钱七", 8800);
            console.writeline("按照姓名排序");
            array.sort(employees);
            foreach (employee em in employees)
            {
                console.writeline(em);
            }
            console.writeline("按照薪水排序");
            array.sort(employees, employee.salarycom);
            foreach (employee em in employees)
            {
                console.writeline(em);
            }
        }
    }
    class employee : icomparable
    {
        private string _name;
        public string name
        {
            get { return _name; }
        }
        private int _salary;
        public int salary
        {
            get { return _salary; }
        }
        public employee(string name, int salary)
        {
            _name = name;
            _salary = salary;
        }
        //显示接口实现
        int icomparable.compareto(object obj)
        {
            if (!(obj is employee))
            {
                throw new argumentexception("不是employee类");
            }
            return _name.compareto(((employee)obj)._name);
        }
        //提供一个公用的强类型重载版本
        public int compareto(employee em)
        {
            return _name.compareto(em._name);
        }
        //当第一次实例化employee的时候,_salarycom为空,当使用salarycom时,就会创建一个salarycompare对象,第2次,3次的时候,就可以直接使用_salarycom了
        private static salarycompare _salarycom = null;
        public static icomparer salarycom
        {
            get
            {
                if (_salarycom == null)
                {
                    _salarycom = new salarycompare();
                }
                return _salarycom;
            }
        }
        //嵌套类(这个类是针对薪水进行排序的类)
        private class salarycompare:icomparer
        {
            //使用指定的icomparer对array中的元素进行排序
            int icomparer.compare(object obj1,object obj2)
            {
                if (!(obj1 is employee) || !(obj2 is employee))
                {
                    throw new argumentexception("不是employee类");
                }
                return ((employee)obj1)._salary.compareto(((employee)obj2)._salary);
            }
        }
        public override string tostring()
        {
            return _name +"  "+ _salary.tostring();
        }
    }
}