工人类(例):
class Worker(
string Name{get;private set;}
int Money{get;private set;}
public Worker(string name,int money) //构造函数
{
this.Name=name;
this.Money=money;
}
public static bool Compare(Worker w1,Worker w2)
{
if(w1.Money>w2.Money)
{
return true;
}
return false;
}
//重写ToString()方法
publiic override string ToString()
{
return Name+" "+Money;
}
}
冒牌排序的拓展方法:
public static void Sort<T>(T[]Array,Func<T,T,bool>Compera) //写一个Sort的泛型方法,定义一个Array的泛型数组,用Func委托来传入要比较的内容
{
bool control=true; // 若control=true 则证明是有序排列,无需继续执行下面代码了
do
{
control=false;
for(int i=0;i<Array.Lenght;i++)
{
if(Compare(Array[i],Array[i+1]))
{
T temp = Array[i];
Array[i]=Array[i+1];
Array[i+1] = temp;
}
}
}While(contorl);
}
实例化:
Worker[] workers=new Worker[]{
new Worker ("张三",215),
new Worker ("李四",845),
new Worker ("王五",263),
new Worker ("赵六",231),
};
//调用Sort方法进行比较
Sort<Worker>(workers,Worker.Compare);//对象为Worker类型,workers为参数,Worker.Compare的返回值类型是bool
//遍历输出结果
foreach(Worker item in workers)
{
Console.WriteLine(item.ToString());
}
Console.Readkey();