扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
以汽车为例:
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实现接口IComparable使其能够使用Array.Sort()。
代码如下:
public class Car:IComparable { 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 成员#region IComparable 成员 public int CompareTo(Car other) { if (this.weight == other.weight) return 0; if (this.weight > other.weight) return 1; return -1; } |
}实现该方法以后我们就可以直接使用如下代码来对cars进行排序了。
Car[] arr = new Car[] {car1,car2,car3 };
Array.Sort
不用担心我们只要使用一个最简单的Adapter模式就能解决这个问题 下面我们来创建这个适配器:
public class ComparaCarAdapter : IComparer { IComparer 成员#region IComparer 成员 public int Compare(Car x, Car y) { return x.Type.CompareTo(y.Type); } |
}然后如此调用:
Array.Sort(arr,new ComparaCarAdapter());但是这样如果属性很多,会产生很多的类,怎么办呢。那么利用反射吧。将ComparaCarAdapter改造为: public class ComparaCarAdapter : IComparer { string _progName = ""; public ComparaCarAdapter(string progName) { _progName = progName; } IComparer 成员#region IComparer 成员 public int Compare(Car x, Car y) { Type t = typeof(Car); PropertyInfo pi = t.GetProperty(_progName); object xvalue = pi.GetValue(x, null); object yvalue = pi.GetValue(y, null); if (xvalue is string) { return ((string)xvalue).CompareTo((string)yvalue); } else { if (xvalue is int) return ((int)xvalue).CompareTo((int)yvalue); } throw new NotSupportedException(); } #endregion } |