C# Gives CS0019 Error: Operator cannot be applied to operands of type 'T' and 'T'

C# Gives CS0019 Error: Operator cannot be applied to operands of type 'T' and 'T'

我正在尝试将 AVL 树转换为通用树,但我遇到了几个类型错误。

Operator cannot be applied to operands of type 'T' and 'T'

 private Node RecursiveInsert(Node current, Node n)
{
    if (current == null)
    {
        current = n;
        return current;
    }
    else if (n.data < current.data) // Gives Error        {
        current.left = RecursiveInsert(current.left, n);
        current = balance_tree(current);
    }
    else if (n.data > current.data) // Gives Error        {
        current.right = RecursiveInsert(current.right, n);
        current = balance_tree(current);
    }
    return current;
}

///

 public class Node
{
    public T data { get; set; }
    public Node left { get; set; }
    public Node right { get; set; }
    public Node(T data)
    {
        this.data = data;
    }
}
public Node root;

编辑:不知何故,我在发布之前设法删除了一段代码。

首先,Node中的泛型类型class需要实现ICompareable接口才能做到这一点。

 public class Node<T> where T : ICompareable
 {
     public T data { get; set; }
     public Node<T> left { get; set; }
     public Node<T> right { get; set; }
     public Node<T>(T data)
     {
         this.data = data;
     }
 }

其次,ICompareable 不会重载“<”和“>”运算符。你需要做这样的事情来代替

else if (n.data.CompareTo(current.data) < 0) {
    current.left = RecursiveInsert(current.left, n);
    current = balance_tree(current);
}

您可以从 Comparer<T>.Default 获得通用比较器。

public class Node
{
    public static readonly IComparer<T> comparer = Comparer<T>.Default;
}

然后你可以用它来比较泛型。

int c = Node.comparer.Compare(n.data, current.data);

if (c < 0) {
    current.left = RecursiveInsert(current.left, n);
    current = balance_tree(current);
}
else if (c > 0) {
    current.right = RecursiveInsert(current.right, n);
    current = balance_tree(current);
}