工人類(例):
class Worker(
string Name{get;private set;}
int Money{get;private set;}
public Worker(string name,int money) //構(gòu)造函數(shù)
{
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) //寫一個(gè)Sort的泛型方法泞遗,定義一個(gè)Array的泛型數(shù)組苟弛,用Func委托來傳入要比較的內(nèi)容
{
bool control=true; // 若control=true 則證明是有序排列习霹,無需繼續(xù)執(zhí)行下面代碼了
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);
}
實(shí)例化:
Worker[] workers=new Worker[]{
new Worker ("張三",215),
new Worker ("李四",845),
new Worker ("王五",263),
new Worker ("趙六",231),
};
//調(diào)用Sort方法進(jìn)行比較
Sort<Worker>(workers,Worker.Compare);//對(duì)象為Worker類型脂倦,workers為參數(shù)伏尼,Worker.Compare的返回值類型是bool
//遍歷輸出結(jié)果
foreach(Worker item in workers)
{
Console.WriteLine(item.ToString());
}
Console.Readkey();