// 员工类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate委托
{
class Employee // 员工类
{
public string Name { get; set; }
public double Salary { get; set; }
public Employee(string name, double salary)
{
Name = name;
Salary = salary;
}
public static bool Compare(Employee e1, Employee e2)
{
return e1.Salary > e2.Salary;
}
}
}
// 冒泡函数
public static void Sort<T>(T[] data, Func<T, T, bool> Compare) // 定义一个泛型 T 为数据类型
{
bool swaped = true; // 循环进行的判断条件
do
{
swaped = false;
for (int i = 0; i < data.Length - 1; i++)
{
if (Compare(data[i], data[i + 1]))
{
T temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
swaped = true;
}
}
} while (swaped);
}
// 调用
Employee[] employees = //定义一个Employee类型数组
{
new Employee("Mack", 20000),
new Employee("Mike", 12000),
new Employee("Lack", 8000),
new Employee("Black", 20000),
new Employee("Mich", 15000)
};
Sort<Employee>(employees, Employee.Compare); // 使用排序
foreach (Employee e in employees)
{
Console.WriteLine(e.Name + ":" + e.Salary);
}
/*
Lack:8000
Mike:12000
Mich:15000
Mack:20000
Black:20000
*/