比较泛型类型

本文关键字:泛型类型 比较 | 更新日期: 2023-09-27 18:09:27

我正在写一个通用二叉搜索树。我需要比较两个泛型。如何实现,假设用户在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) 
{
   //...
}

使用where子句,即

class Node<T> where T : IComparable
http://msdn.microsoft.com/en-us/library/bb384067.aspx