在.NET中的二分查找算法(在列表,数组等)出现故障,如果你想搜索的项目从IComparable的继承直接实现它,而不是:C#BinarySearch从实现IComparable <T>的东西继承时破坏?
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)似乎不起作用。
此代码在我的C#编译器上生成运行状况良好 – Stewart 2010-05-02 04:57:26
@Stewart - 您可能正在使用C#4. – Kobi 2010-05-02 05:16:41
@Kobi - 哎呀,很对。我忘了这个改变了,问题没有提到一个版本。 – Stewart 2010-05-02 05:38:12