我正在尝试创建通用节点对象的通用树类。
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);
}
}
但是在主方法中我收到编译错误:
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<>
上类 - 你说过 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<Node<int>>
.
但实际创建一个 Tree<int>
可能会更好,并制作 Tree<T>
使用Node<T>
相反。这可能更容易使用。毕竟,每棵树都会有节点。用相对较少的代码很难确定,但我怀疑这实际上就是您想要做的。
关于c# - 通用节点的通用树 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59388140/