2016-06-12 86 views
0

我想在C#中使用泛型实现二叉搜索树,但我不知道如何实现IComparable接口。我不能比较通用类型T,所以我不知道如何实现CompareTo()函数。C#泛型类型和IComparable,无法比较类型T

下面是代码:

public class BSTNode<T> : IComparable<BSTNode<T>> 
{ 
    public T Data { get; set; } 
    public BSTNode<T> LeftChild { get; private set; } 
    public BSTNode<T> RightChild { get; private set; } 

    ... 
} 

当试图实现public void Insert(BSTNode<T> node),我需要比较Data财产,但我得到一个错误说我不能比较泛型类型T.

我试图执行IComparable接口,但在CompareTo函数中,它与T错误无法相比。任何想法如何解决这个问题?

+1

你应该确保'T'也实现'IComparable'。 – Tdorno

+0

我看到了这个问题,但我得到一个错误,说类型T没有CompareTo成员函数。 – Naz

+1

'public class BSTNode :IComparable > where T:IComparable' – Tdorno

回答

2

如果你添加一个约束到你的泛型类型,那就行了。

public class BSTNode<T> : IComparable<BSTNode<T>> where T : IComparable<T> 
{ 
    public T Data { get; set; } 
    public BSTNode<T> LeftChild { get; private set; } 
    public BSTNode<T> RightChild { get; private set; } 

    public int CompareTo(BSTNode<T> other) 
    { 
     return this.Data.CompareTo(other.Data); 
    } 
} 
1

你需要的是一个泛型类型约束:

public class BSTNode<T> : IComparable<BSTNode<T>> 
    where T : IComparable<T> 

,可以让你在Data调用CompareTo