“无法转换为IComparer”

时间:2009-09-28 13:58:04

标签: c# icomparer

我为盒装的RegistryItem对象定义了以下IComparer:

public class BoxedRegistryItemComparer : IComparer<object>
{
    public int Compare(object left, object right)
    {
        RegistryItem leftReg = (RegistryItem)left;
        RegistryItem rightReg = (RegistryItem)right;

        return string.Compare(leftReg.Name, rightReg.Name);
    }
}

我想用它来对盒装的RegistryItems的ArrayList进行排序(它确实应该是一个List <RegistryItem&gt;,但这是我无法控制的。)

ArrayList regItems = new ArrayList();
// fill up the list ...
BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer();
ArrayList.sort(comparer);

但是,最后一行给出了编译器错误:“无法从BoxedRegistryItemComparer转换为System.Collections.IComparer”。如果有人可以指出我的错误,我将不胜感激。

6 个答案:

答案 0 :(得分:8)

BoxedRegistryItemComparer应实施System.Collections.IComparer以与ArrayList.Sort一起使用。你实现了System.Collections.Generic.IComparer<T>这不是一回事。

答案 1 :(得分:7)

您已定义Generic-Comparer (IComparer<T>)而不是Comparer without a type (IComparer)ArrayList.Sort()需要非通用的IComparer

Generic-Types不能被转换为非泛型等价物。

答案 2 :(得分:3)

如果您遇到无法控制Comparer或Sorter的情况,这里有两个迷你类可以在两种类型之间进行转换(未经测试):

private class GenericComparer<T> : IComparer<T>
{
    IComparer _Comparer;
    public GenericComparer(IComparer comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(T a, T b)
    {
        return _Comparer.Compare(a, b);
    }
}

private class NonGenericComparer<T> : IComparer
{
    IComparer<T> _Comparer;
    public NonGenericComparer(IComparer<T> comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(object a, object b)
    {
        return _Comparer.Compare((T)a, (T)b);
    }
}

答案 3 :(得分:1)

也许这是一个拐杖,但它有效:

            arrayList.Sort(Comparer<object>.Create(
            (x, y) => ((RegistryItem)x).Name.CompareTo(((RegistryItem)y).Name)));

答案 4 :(得分:0)

public class BoxedRegistryItemComparer : IComparer {
...
}

答案 5 :(得分:0)

上述帖子的替代方法是让您的比较器类实现两个接口,然后您可以转换IComparer&lt; T&gt;如果你需要两者,你可以选择IComparer。

public class MyComparer<T> : IComparer<T>, IComparer