我正在编写通用二进制搜索树。我需要比较两种通用类型。假设用户已经在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);
}

最佳答案

您必须在方法中添加通用约束where T: IComparable<T>,以使CompareTo()方法可用于类型为T的实例。

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


然后,您可以使用:

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

10-07 16:02