以汽车为例:
public class Car: {
private int weight;
public int Weight
{
get { return weight; }
set { weight = value; }
}
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
}Car[] cars;现在需要排序,首先我们想根据Weight进行排序,大家自然会想到冒泡算法。不过这个肯定不是最好的,这里提供一个简便的方法。
我们将类Car实现接口IComparable使其能够使用Array.Sort()。
代码如下:
public class Car:IComparable<Car>
{
private int weight;
public int Weight
{
get { return weight; }
set { weight = value; }
}
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
IComparable
}
Car[] arr = new Car[] {car1,car2,car3 };
Array.Sort<Car>(arr);不用担心我们只要使用一个最简单的Adapter模式就能解决这个问题
下面我们来创建这个适配器:
public class ComparaCarAdapter : IComparer<Car>
{
IComparer
}
Array.Sort<Car>(arr,new ComparaCarAdapter());
public class ComparaCarAdapter : IComparer<Car>
{
string _progName = "";
public ComparaCarAdapter(string progName)
{
_progName = progName;
}
IComparer
}调用
Array.Sort<Car>(arr, new ComparaCarAdapter("Weight"));(转载请通知并注明出处。)

