2011-09-23 85 views
1

我正在编写通用二进制搜索树。我需要比较两种泛型类型。如何做到这一点,假设用户在T类中实现了IComparable比较通用类型

private void Insert(T newData, ref Node<T> currentRoot) 
{ 
    if (currentRoot == null) 
    { 
     currentRoot = new Node<T>(newData); 
     return; 
    } 
    if (newData <= currentRoot.data) //doesn't work, need equivalent functionality 
     Insert(newData, ref currentRoot.lChild); 
    else 
     Insert(newData, ref currentRoot.rChild); 
} 
+0

不'newData.CompareTo(currentRoot.data)'工作? –

+0

只能用'where T:IComparable '作为@BrokenGlass指出的 – devnull

回答

6

你必须通用约束where T: IComparable<T>添加到您的方法来提供给您的T类型的实例CompareTo()方法。

private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T> 
{ 
    //... 
} 

然后你可以使用:

if (newData.CompareTo(currentRoot.data) <= 0) 
{ 
    //... 
} 
+0

拍摄时,你更快 –

+0

@BrokenGlass谢谢,那有效。 – devnull

1

使用where条款,即

class Node<T> where T : IComparable 

http://msdn.microsoft.com/en-us/library/bb384067.aspx

+0

这个答案是不完整的,只是提供一个约束不允许用户尝试的代码行。幸运的是,BrokenGlass添加了一个合适的示例解决方案。 –

+0

我明白了。我的C#有点生疏;) –