让我们实现一个简单的扩展方法:
public static partial class ComparerExtensions {
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
if (null == comparer)
throw new ArgumentNullException(nameof(comparer));
return Comparer<T>.Create((left, right) => comparer.Compare(right, left));
}
}
然后你可以反转任何你喜欢的比较器(ICompare<T>
):
MyList.Sort(YourCustomComparer.Reverse());
在你的情况下(比较器实现有点奇怪 IDisposable
):
using (var naturalComparer = new NaturalComparer()) {
contents.Sort(naturalComparer.Reverse());
}
编辑:如果是 C# 4.0 或更早版本(没有 Comparer<T>.Create
),我们可以像这样实现扩展方法:
public static partial class ComparerExtensions {
private sealed class ReversedComparer<T> : IComparer<T> {
private readonly IComparer<T> m_Comparer;
public ReversedComparer(IComparer<T> comparer) {
m_Comparer = comparer;
}
public int Compare(T x, T y) {
return m_Comparer.Compare(y, x);
}
}
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
if (null == comparer)
throw new ArgumentNullException(nameof(comparer));
return new ReversedComparer<T>(comparer);
}
}
我是一名优秀的程序员,十分优秀!