Sorting Winforms TreeView in a type safe way?
Is it possible to sort a TreeView
collection using IComparer<T>
and not IComparer
? After all they are all T开发者_开发技巧reeNode
values, right?
If you mean via TreeViewNodeSorter
, then it must be an IComparer
(in short, it pre-dates generics). You could write something that shims this, but it probably isn't worth the trouble...
public static class ComparerWrapper
{ // extension method, so you can call someComparer.AsBasicComparer()
public static IComparer AsBasicComparer<T>(this IComparer<T> comparer)
{
return comparer as IComparer
?? new ComparerWrapper<T>(comparer);
}
}
sealed class ComparerWrapper<T> : IComparer
{
private readonly IComparer<T> inner;
public ComparerWrapper(IComparer<T> inner)
{
if (inner == null) throw new ArgumentNullException("inner");
this.inner = inner;
}
int IComparer.Compare(object x, object y)
{
return inner.Compare((T)x, (T)y);
}
}
One thing that tripped me up was that IComparer comes from System.Collections whereas IComparer comes from System.Collections.Generic.
I originally only had
using System.Collections.Generic;
and was getting a compile error:
Cannot implicitly convert type 'MyApp.NodeSorter' to 'System.Collections.IComparer'. An explicit conversion exists (are you missing a cast?)
The solution was to add
using System.Collections;
精彩评论