我正在使用以下代码实现二叉树:
class Binary<T>:Binary
where T: IComparable
{
但我也想在树中使用类对象:
Binary Bin = null;
Bin = new Binary<Product>();
这显然不起作用,因为Product
不是IComparable
。我尝试这样做是为了让它起作用:
public class Product: IComparable<Product>
{
public int Id = 0;
public int CompareTo(Product p)
{
if (p==null)
{
return 1;
}
if (p!=null)
{
return this.Id.CompareTo(p.Id);
}
return 0;
}
Id
是旨在用于所有比较的Product
的值。但这不起作用,我不知道还能做什么。有可能做我想要的吗?或者是否有另一种方法可以将课程Product
用作IComparable
?
答案 0 :(得分:3)
您的班级Product
实现了通用IComparable<T>
,其中您的泛型类Binary<T>
需要实现非泛型IComparable
的泛型类型。
更新Binary<T>
声明以在约束中使用IComparable<T>
:
class Binary<T>:Binary
where T: IComparable<T>
{