“无法转换为 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
ArrayList regItems = new ArrayList();
// fill up the list ...
BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer();
ArrayList.sort(comparer);
但是,最后一行给出了编译器错误:“无法从 BoxedRegistryItemComparer 转换为 System.Collections.IComparer”。如果有人能指出我的错误,我将不胜感激。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
BoxedRegistryItemComparer
应该实现System.Collections.IComparer
以便与ArrayList.Sort
一起使用。您实现了 System.Collections.Generic.IComparerBoxedRegistryItemComparer
should implementSystem.Collections.IComparer
to be used withArrayList.Sort
. you implementedSystem.Collections.Generic.IComparer<T>
which is not the same thing.您已定义通用比较器 (
IComparer;)
而不是 没有类型的比较器(
IComparer
)。ArrayList.Sort()
需要一个非通用的
IComparer
。泛型类型不能转换为其非泛型等价物。
You've defined a Generic-Comparer (
IComparer<T>
) instead of a Comparer without a type (IComparer
).ArrayList.Sort()
expects a non-genericIComparer
.Generic-Types can not be casted into their non-generic equivalents.
如果您无法控制比较器或排序器,这里有两个迷你类可以在两种类型之间进行转换(未经测试):
In case you have a situation where you don't have any control over the Comparer or the Sorter, here are two mini-classes which can convert between the two types (untested):
也许它是一个拐杖,但它确实有效:
Perhaps it is a crutch, but it works:
上述帖子的替代方法是让您的比较器类实现这两个接口,然后您可以将 IComparer 强制转换为如果您两者都需要,请转到 IComparer。
An alternative to above post would be to have your comparer class implement both interfaces, then you can cast IComparer<T> to IComparer should you need both.