在c#中将转换和对象类转换为IComparable

时间:2015-03-15 01:20:40

标签: c# icomparable

我正在使用以下代码实现二叉树:

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

1 个答案:

答案 0 :(得分:3)

您的班级Product实现了通用IComparable<T>,其中您的泛型类Binary<T>需要实现非泛型IComparable的泛型类型。

更新Binary<T>声明以在约束中使用IComparable<T>

class Binary<T>:Binary
   where T: IComparable<T>
{