【发布时间】:2010-05-02 04:45:17
【问题描述】:
在 .NET 中,如果您尝试搜索的项目继承自 IComparable 而不是直接实现它,则 BinarySearch 算法(在列表、数组等中)似乎会失败:
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 - 你可能正在使用 C# 4。
-
@Kobi - 哎呀,完全正确。我忘了这已经改变了,问题没有提到版本。
标签: c# generics inheritance sorting interface