ITPub博客

首页 > IT职业 > IT生活 > 利用委托对不同类型的对象数组排序

利用委托对不同类型的对象数组排序

IT生活 作者:jasonhsp 时间:2021-09-09 09:15:04 0 删除 编辑
  1using System;
  2using System.Collections.Generic;
  3using System.Text;
  4
  5namespace delegateTest
  6{
  7    /// 
  8    /// 演示利用委托给不同类型的对象排序
  9    /// 
 10    class Program
 11    {
 12        delegate bool CompareOp(object lhs,object rhs);//声明委托(注意方法签名的格式是两个object类型参数)
 13
 14        static void Main(string[] args)
 15        {
 16            Employee[] employees = {
 17                new Employee("Bugs Bunny",20000),
 18                new Employee("Elmer Fudd",10000),
 19                new Employee("Daffy Duck",25000),
 20                new Employee("Wiley Coyote",(decimal)1000000.38),
 21                new Employee("Foghorn Leghorn",23000),
 22                new Employee("Road Runner",50000)
 23            };
 24
 25            CompareOp c1 = new CompareOp(Employee.CompareEmploySalary);
 26
 27            BubbleSorter.Sort(employees, c1);//对employees数组,按工资高低排序
 28
 29            for (int i = 0; i 
 51        /// 比较整数的大小
 52        /// 
 53        /// 整数1
 54        /// 整数2
 55        /// 如果第一个数小于第二数,返回true,反之false
 56        static bool CompareInt(object x, object y) 
 57        { 
 58            return (int)y>(int)x?true:false;
 59        }
 60
 61        /// 
 62        /// 冒泡排序类
 63        /// 
 64        class BubbleSorter
 65        {
 66            static public void Sort(object[] sortArray, CompareOp gtMethod)
 67            {
 68                for (int i = 0; i 
 87    /// 员工实体类
 88    /// 
 89    class Employee 
 90    {
 91        private string name;
 92        private decimal salary;
 93
 94
 95        /// 
 96        /// Employee构造函数
 97        /// 
 98        /// 
 99        /// 
100        public Employee(string name, decimal salary) 
101        {
102            this.name = name;
103            this.salary = salary;
104        }
105
106        /// 
107        /// 覆盖ToString()方法
108        /// 
109        /// 
110        public override string ToString()
111        {
112            return string.Format(name + ",{0:c}", salary);
113        }
114
115        /// 
116        /// 按员工工资高低比较大小
117        /// 
118        /// 
119        /// 
120        /// 
121        public static bool CompareEmploySalary(object lhs, object rhs) 
122        {
123            Employee empLhs = (Employee)lhs;
124            Employee empRhs = (Employee)rhs;
125            return (empRhs.salary > empLhs.salary) ? true : false;
126        }
127    }
128}


运行结果:
Elmer Fudd,¥10,000.00
Bugs Bunny,¥20,000.00
Foghorn Leghorn,¥23,000.00
Daffy Duck,¥25,000.00
Road Runner,¥50,000.00
Wiley Coyote,¥1,000,000.38
---------------------------------------
0
2
3
5
6
8
---------------------------------------

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/615/viewspace-2801220/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    342
  • 访问量
    2721