I am implementing a class that in the style of the LINQ libraries has an overload for a custom IComparer. (e.g. OrderBy: OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)
and OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>)
).
I would like to implement 开发者_如何学Cthe 2-argument overload in terms of the 1-argument overload. Something like the following:
T Method<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
// Do something that returns a T
}
T Method<T>(IEnumerable<T> collection) where T: IComparable<T>
{
IComparer<T> comparer = /*what goes here?*/;
return Method(collection, comparer);
}
In this respect, the question boils down to asking, how do I obtain an instance of IComparer for a type that implements IComparable?
You are looking for Comparer<T>.Default
.
精彩评论