c#泛型排序
泛型排序用于多类对象结构体分别排序的情况,也算是进一步了解委托。
class Program
{
static void Main(string[] args)
{
Student[] stu = {
new Student("stu1", 40),
new Student("stu2", 50),
new Student("stu3", 46),
new Student("stu4", 83),
new Student("stu5", 93),
new Student("stu6", 29)};
TSort<Student>(stu, Student.Compare);
foreach (var item in stu)
{
Console.WriteLine(item.ToString());
}
}
static private void TSort<T>(T[] tt,Func<T,T,int> compare)//委托的使用
{//泛型冒泡排序
for (int i = 0; i < tt.Length-1; i++)
{
for (int j = 0; j < tt.Length-i-1; j++)
{
if (compare(tt[j],tt[j+1])>0)
{
T temp = tt[j + 1];
tt[j + 1] = tt[j];
tt[j] = temp;
}
}
}
}
}
class Student
{//prop
public string name { get; private set; }
public int score { get;private set; }
public Student(string name,int score)
{//ctor
this.name = name;
this.score = score;
}
public override string ToString()
{
return name+":"+score;
}
static public int Compare(Student stu1,Student stu2)
{//静态方法和非静态方法的区别,非静态方法只能通过实例化对象.调用,
//非静态方法可通过类.调用,因而二者生命周期也不一样
if (stu1.score<stu2.score)
{
return -1;
}
else if(stu1.score>stu2.score)
{
return 1;
}
else
{
return 0;
}
}
}