在.NET中,如果您尝试搜索的项目从IComparable继承而不是直接实现,则BinarySearch算法(在列表,数组等中)似乎会失败: ListB foo = new ListB(); // B inherits from A, which implements IComparableAfoo.Add(new B());
List<B> foo = new List<B>(); // B inherits from A, which implements IComparable<A> foo.Add(new B()); foo.BinarySearch(new B()); // InvalidOperationException, "Failed to compare two elements in the array."
哪里:
public abstract class A : IComparable<A> { public int x; public int CompareTo(A other) { return x.CompareTo(other.x); } } public class B : A {}
有没有解决的办法?在B类中实现CompareTo(B other)似乎不起作用.
文档清楚地说明了这一点:checks whether type T implements the IComparable generic interface and uses that implementation, if available. If not, Comparer.Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer.Default throws an InvalidOperationException.
因此,一个简单的解决方案是实现非通用接口IComparable.
添加CompareTo(B other)将对您有用,只要您还实现IComparable< B> – 你可能忘了那一点.
一个有趣的解决方案是使用C#4编译代码,它运行时没有任何错误. C#4引入了通用协方差:公共接口IComparable< in T> vs公共接口IComparable< T>,并且发布的代码按预期工作.