码迷,mamicode.com
首页 > Windows程序 > 详细

C#委托冒泡

时间:2017-04-15 20:10:40      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:container   rri   sharp   write   委托方   code   实体类   order   index   

委托的实现,就是编译器自行定义了一个类:有三个重要参数1.制定操作对象,2.指定委托方法3.委托链

看如下一个列子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class DelegatePratice
   {
       public static void Sort<T>(IList<T> sortArray, Func<T, T, bool> Comparison)
       {
           bool swapped = true;
           do
           {
               swapped= false;
               for (int i = 0; i < sortArray.Count - 1; i++)
               {
                   if (Comparison(sortArray[i], sortArray[i + 1]))
                   {
                       T temp = sortArray[i];
                       sortArray[i] = sortArray[i + 1];
                       sortArray[i + 1] = temp;
                       swapped = true;
                   }
               }
           while (swapped);
           
       }
   }<br><br>定义实体类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Employee
    {
        public Employee(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }
        public string Name
        {
            get;
            set;
        }
        public decimal Salary
        {
            get;
            set;
        }
        /// <summary>
        /// 重写object的ToString方法
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("{0},{1:C}",Name,Salary);
        }
         
        /// <summary>
        /// 比较两员工的工资以此排序
        /// </summary>
        /// <param name="e1"></param>
        /// <param name="e2"></param>
        /// <returns></returns>
        public static bool Comparison(Employee e1, Employee e2)
        {
            return e1.Salary > e2.Salary;
        }
    }<br><br>

 调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Program
    {
        static void Main(string[] args)
        {
            Employee[] employees = { new Employee("simen", 5500), new Employee("shelly", 5900),
                new Employee("pool", 4300), new Employee("renata", 3800) };
            DelegatePratice.Sort(employees, Employee.Comparison);
            foreach (Employee employee in employees)
            {
                Console.WriteLine(employee);
            }
            Console.ReadKey();
        }
    }
}

C#委托冒泡

标签:container   rri   sharp   write   委托方   code   实体类   order   index   

原文地址:http://www.cnblogs.com/chenshizhutou/p/6715361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!