【问题标题】:Generic tree of generic node C#通用节点 C# 的通用树
【发布时间】:2019-12-18 08:30:15
【问题描述】:

我正在尝试创建通用节点对象的通用树类。

using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Tree<Node<int>> tree = new Tree<Node<int>>();
    }
}

public class Tree<T> : IEnumerable<T>
    where T : IComparable<T>
{
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

public class Node<TNode> : IComparable<TNode>
    where TNode : IComparable<TNode>
{
    TNode Value;
    public int CompareTo(TNode other)
    {
        return Value.CompareTo(other);
    }
}

但在 main 方法中我收到编译错误:

The type 'BinaryTree.Node<int>' cannot be used as type parameter 'T' in the generic type or method 'Tree<T>'. There is no implicit reference conversion from 'BinaryTree.Node<int>' to 'System.IComparable<BinaryTree.Node<int>>'.

谁能帮我理解问题出在哪里?

【问题讨论】:

  • 您已声明Node&lt;T&gt; 可以与T 进行比较。你需要:class Node&lt;TNode&gt; : IComparable&lt;Node&lt;TNode&gt;&gt;(注意我在界面中添加了 Node)
  • 这意味着我可以将节点与节点进行比较,但我想做的是使用 IComparable 接口将节点值与其他值进行比较

标签: c# .net generics


【解决方案1】:

问题出在您的 Node&lt;&gt; 类中 - 您已经说过 Node 与其中的值类型相当。相反,你应该说它与另一个具有相同值的 node 相当:

public class Node<TNode> : IComparable<Node<TNode>>
    where TNode : IComparable<TNode>
{
    TNode Value;
    public int CompareTo(Node<TNode> other)
    {
        return Value.CompareTo(other.Value);
    }
}

此时,它会创建一个Tree&lt;Node&lt;int&gt;&gt;

但实际上创建一个Tree&lt;int&gt; 并让Tree&lt;T&gt; 在内部使用Node&lt;T&gt; 可能会更好。这可能更容易使用。毕竟,每棵树都会有节点。使用相对较少的代码很难确定,但我怀疑这实际上是您想要做的。

【讨论】:

    【解决方案2】:

    我猜你和我一样被你的命名标准弄糊涂了。

    这个声明有问题:

    public class Node<TNode> : IComparable<TNode>
        where TNode : IComparable<TNode>
    

    让我们通过重命名泛型参数来重写它:

    public class Node<T> : IComparable<T>
        where TNode : IComparable<T>
    

    在这里您可以看到您声明它可以与它存储的值进行比较,而不是与其他节点进行比较。

    由于树类型需要 its T 能够与相同类型的值进行比较,因此您需要节点能够与其他节点进行比较,如下所示:

                                       changed
                                       v-----v
    public class Node<T> : IComparable<Node<T>>
        where TNode : IComparable<TNode>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2014-12-21
      • 1970-01-01
      相关资源
      最近更新 更多