public class People
{
public string Name { get; set; }
public int Age { get; set; }
public People(string name, int age)
{
Name = name;
Age = age;
}
public static bool CompareAge(People p1, People p2)
{
return p1.Age < p2.Age;
}
public override string ToString()
{
return string.Format("[people] name:{0},age:{1}", Name, Age);
}
}
Student:
public class Student
{
public string Name { get; set; }
public float Score { get; set; }
public Student(string name, float score)
{
Name = name;
Score = score;
}
public static bool CompareScore(Student s1, Student s2)
{
return s1.Score < s2.Score;
}
public override string ToString()
{
return string.Format("[student] name:{0},score:{1}",Name,Score);
}
}
冒泡排序的實現,如果對Fun<>的委托寫法不懂,最後有說明。
public static class Storter_Fun
{
public static void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparision)
{
bool swapped = true;
do
{
swapped = false;
for (int i = 0; i < sortArray.Count - 1; i++)
{
if (comparision(sortArray[i + 1], sortArray[i]))
{
T temp = sortArray[i];
sortArray[i] = sortArray[i + 1];
sortArray[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
控制台,使用排序:
static void Main(string[] args)
{
//人按年齡排序
People[] peoples = {new People("張三",43),
new People("李四",12),
new People("王五",50),
new People("吳六",21),
new People("陳七",33),};
//Fun<>委托的寫法
BubbleSorter.Storter_Fun.Sort<People>(peoples, People.CompareAge);
//匿名方法的寫法
BubbleSorter.Storter_Fun.Sort<People>(peoples, delegate(People p1, People p2)
{
return p1.Age < p2.Age;
});
//Lambdah表達式的寫法
BubbleSorter.Storter_Fun.Sort<People>(peoples, (People p1, People p2) =>
{
return p1.Age < p2.Age;
});
foreach (var people in peoples)
{
Console.WriteLine(people);
}
//學生按分數排序
Student[] students = {new Student("張三",80.5F),
new Student("李四",85),
new Student("王五",88),
new Student("吳六",70),
new Student("陳七",95),};
BubbleSorter.Storter_Fun.Sort<Student>(students, Student.CompareScore);
foreach (var student in students)
{
Console.WriteLine(student);
}
Console.ReadKey();
}
委托:調用方法的參數一般情況是數值型的,例如int,string,DataTable等等,能不能將方法本身作為一個參數傳遞給另一個方法呢?委托就是解決這個問題的。 既然是參數,要就有類型。C#是強類型,方法的參數是int類型,就不能傳string類型進去,否則在編輯階段就報錯了。 int,string等是已有的類型,委托的類型就需要自定義。 例如上面例子用到的: Fun 代表方法是傳入兩個泛型參數,返回bool; Fun 代表方法是傳入三個參數:int, string,DataTable,返回Array; 就是最後一個參數為返回值類型; 那麼如果沒有返回值呢? Action 代表方法是傳入兩個泛型參數,沒返回值 Action 代表方法是傳入兩個參數:int,string,沒返回值 定義了委托的類型,傳入的方法必須要符合這個定義,即:傳入參數,類型,個數,順序,返回值要一致,否則編譯不過,C#是強類型的原因。 剛實現的冒泡可以支持不同對象的排序,主要是將冒泡比較大小方法傳遞進來(委托),與交換數據的臨時變量使用了泛型實現;