using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace detegateClass1 { class Student { private string name; private decimal score; public Student(string name, decimal score) { this.name = name; this.score = score; } /// <summary> /// 其中的一个比较方法,因为学生分数的比较,可能要比较多门学科,所以,这里这是列出其中的一们学科的比较方法。 /// 委托就是要解决这种问题。 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool methodA(object a, object b) { Student sa = (Student)a; Student sb = (Student)b; return (sa.score > sb.score) ? true : false; } public override string ToString() { return string.Format(name+" : " + score); } } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DelegateMethood = detegateClass1.Program.DelegateMethood;
namespace detegateClass1
{
class ScoreSort
{
/// <summary>
/// 这里采用冒泡比较法,由于比较的学科很多,所以要加入一个参数,要代表比较的是哪门的学科
/// 由于这是一个"业务类",应该注重抽象的,不应涉及具体的东西,所以,这里可以用委托方法作为参数
/// </summary>
public static void sort(object[] array,DelegateMethood method) {
for (int i = 0; i < array.Length; i++) {
for (int j = i + 1; j < array.Length; j++) {
if (method(array[j], array[i])) {
object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace detegateClass1
{
class Program
{
public delegate bool DelegateMethood(object a,object b);
static void Main(string[] args)
{
Student[] students = {
new Student("A",100),
new Student("B",90),
new Student("C",80),
new Student("D",70),
new Student("E",60),
new Student("F",50),
new Student("G",40)
};
//在这里用定义的委托,进行方法的包装
DelegateMethood dm = new DelegateMethood(Student.methodA);
ScoreSort ss = new ScoreSort();
for (int i = 0; i < students.Length; i++) {
Console.WriteLine(students[i].ToString());
}
Console.ReadLine();
}
}
}