c# - C# : operator '<' cannot be applied to operands of type 'T' and 'T' 中的比较

标签 c# generics

我创建了一个 BinaryTreeNode<T> 类,然后创建 Add(T data) 的方法 BinaryTree<T> 类。

当我尝试比较对象的值时,编译器说:

operator '<' cannot be applied to operands of type 'T' and 'T'.

例子:

  public void AddNode(T data) {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (temp.Value < node.Value) // **PROBLEM HERE**
        ...

我使用的是 VS08 快捷版。

最佳答案

你应该添加一个约束,使得 T 必须实现 IComparable<T>然后使用它:

public class BinaryTree<T> where T : IComparable<T>
{
    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (temp.Value.CompareTo(node.Value) < 0)
        ...

另一种方法是传入一个 IComparer<T>并使用它:

public class BinaryTree<T> where T : IComparable<T>
{
    private readonly IComparer<T> comparer;

    public BinaryTree(IComparer<T> comparer)
    {
        this.comparer = comparer;
        ...
    }

    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (comparer.Compare(temp.Value, node.Value) < 0)

这是最接近保证“<”运算符的方法 - 重载运算符是静态的,并且无法限制类型参数以要求它。

关于c# - C# : operator '<' cannot be applied to operands of type 'T' and 'T' 中的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1308002/

相关文章:

java - 在非泛型类中采用 List 的泛型方法

java - Apache Commons BeanUtils 获取列表属性

java - 有界 Java 泛型无法编译

Java - 使用泛型创建流畅的界面

c# - 将 Web api blob 读入字符串,我可以将其作为 json 对象的一部分发送到服务器并返回到文件

c# - 有没有办法将 Controller 的 ModelState 传递(或访问)到 ActionFilterAttribute?

c# - 接受任何 SSL 证书

c# - 如何在 C# 中获取日期范围内的所有周末

c# - 从静态 [WebMethod] 访问 ASP.NET 控件(JS ajax 调用)

java - 在运行时解析泛型变量时如何避免未经检查的强制转换?