是否可以使用TreeView而不是IComparer<T>IComparer集合进行排序?毕竟它们都是TreeNode值,对不对?

最佳答案

如果通过TreeViewNodeSorter表示,则它必须是IComparer(简而言之,它早于泛型)。您可以写一些令其感到震惊的东西,但这可能不值得麻烦...

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);
    }
}

关于c# - 以类型安全的方式对Winforms TreeView进行排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2479778/

10-12 20:08