C#委托冒泡

时间:2023-03-08 21:44:40

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

看如下一个列子:

 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); }
} 定义实体类:
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;
}
}

 调用

 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();
}
}
}