学委托必懂的例子
此例子采用委托来排序,整体思路如下:
建一Sorter类,用意是对所有的对象数组排序,不论这个对象是什么类型,只要它满足了Sorter类中的带的一个委托即可,然后新建一个员工类,用这个Sorter类来对一堆员工的工资进行排序.
好了,第一步,新建Sorter类:
1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace BubbleSorter26


{7
class Sorter8

{9
// 参数内的对象比较的方法10
public delegate bool IsGreater(object a,object b);11
// 采用冒泡比较的方法对对象数组内的对象进行比较12
public static void Sort(object[] objs, IsGreater Compare)13

{14
for (int i = 0; i < objs.Length-1; i++)15

{16
bool flag = false;17
object temp;18
if (!flag)19

{20
for (int j = objs.Length - 1; j > i; j--)21

{22
if (!Compare(objs[j], objs[j - 1]))23

{24
temp = objs[j - 1];25
objs[j - 1] = objs[j];26
objs[j] = temp;27
}28
flag = true;29
}30
}31
}32
}33
}34
}
第二步,新建员工类:
1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace BubbleSorter26


{7
class Employee8

{9
private string name;10
private decimal salary;11

12
public Employee(string par_name,decimal par_salary)13

{14
name = par_name;15
salary = par_salary;16
}17
public string Name18

{19
get20

{21
return this.name;22
}23
set24

{25
name = value;26
}27
}28
public decimal Salary29

{30
get31

{32
return salary;33
}34
set35

{36
salary = value;37
}38
}39

40
// 这里满足了Sorter类要求的排序委托,也就是提供一个比较两个员工工资的方法41
public static bool IsGeater(object a, object b)42

{43
if (((Employee)a).salary >= ((Employee)b).salary)44

{45
return true;46
}47
else48

{49
return false;50
}51
}52
}53
}54

最后在主函数内进行调用
1
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Collections;5

6
namespace BubbleSorter27


{8
class Program9

{10
static void Main(string[] args)11

{12
// 这里用代码新建几个员工13
Employee[] employees =14

{15
new Employee("Mr a",40000),16
new Employee("Miss b",5000),17
new Employee("Mrs c",10000),18
new Employee("BOSS d",4000000),19
new Employee("Sir e",300000),20
new Employee("boy f",444444) 21
};22

23
PrintValues(employees);24
Sorter.Sort(employees, Employee.IsGeater);25
PrintValues(employees);26

27
Console.ReadKey();28
}29

30
public static void PrintValues(IEnumerable myList)31

{32
foreach (object obj in myList)33

{34
Console.WriteLine("{0}", ((Employee)obj).Salary);35
}36
Console.WriteLine();37
}38
}39
}40

大功告成.

浙公网安备 33010602011771号