首页 > 代码库 > C#委托冒泡
C#委托冒泡
委托的实现,就是编译器自行定义了一个类:有三个重要参数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#委托冒泡
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。