如果有一个person的类型数组,需要排序,我们想按年龄排序
则使用如下方法
Array.sort(list,(p1,p2)=>p1.age.CompareTo(p2.age));
以前知道,自定义排序需要让自己的类实现IComparer接口,写出自己的排序规则
可是,传递一个委托变量进去(这里用的lamda表达式),.net是如何为我们排序的呢?
请看 Reflector
public static void Sort < T > (T[] array, Comparison < T > comparison){ if (array == null ) { throw new ArgumentNullException( " array " ); } if (comparison == null ) { throw new ArgumentNullException( " comparison " ); } IComparer < T > comparer = new FunctorComparer < T > (comparison); Sort < T > (array, comparer);}
我们看到这里new了一个 FunctorComparer<T>(comparison),并把我们的委托变量传递进去
那么这个类是怎么样的呢
internal sealed class FunctorComparer < T > : IComparer < T > { // Fields private Comparer < T > c; private Comparison < T > comparison; // Methods public FunctorComparer(Comparison < T > comparison) { this .c = Comparer < T > .Default; this .comparison = comparison; } public int Compare(T x, T y) { return this .comparison(x, y); }}
原来它帮我们实现了 IComparer<T>接口,并且用我们传递的排序规则来实现Compare(T x, T y)
接着调用Sort<T>(array, comparer)这个重载
接着又调用4个参数的重载如下
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] public static void Sort < T > (T[] array, IComparer < T > comparer){ if (array == null ) { throw new ArgumentNullException( " array " ); } Sort < T > (array, 0 , array.Length, comparer);}
再继续。。原来微软也喜欢用 XXhelper命名
ArraySortHelper < T > .Default.Sort(array, index, length, comparer);
最后用快速排序算法完成。。
转载于:https://www.cnblogs.com/renjuwht/archive/2010/01/20/1652023.html
