C#中的比较:运算符'<'不能应用于'T'和'T'类型的操作数 [英] Comparison in C#: operator '<' cannot be applied to operands of type 'T' and 'T'
问题描述
我创建了 BinaryTreeNode< T>
类,然后创建了 Add(T data)
方法用于 BinaryTree< T>
类。
I have created a BinaryTreeNode<T>
class and then creating Add(T data)
method for BinaryTree<T>
class.
当我尝试比较对象的值时,编译器会说:
When I try to compare Values of objects compiler says:
运算符'<'不能用于'T'和'T'类型的操作数。
operator '<' cannot be applied to operands of type 'T' and 'T'.
示例:
Example:
public void AddNode(T data) {
BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
BinaryTreeNode<T> temp = root;
if (temp.Value < node.Value) // **PROBLEM HERE**
...
我使用的是VS08 Express Edition。
I'm using VS08 Express Edition.
推荐答案
约束条件,使得T必须实现 IComparable< T>
,然后使用它:
You should add a constraint such that T must implement IComparable<T>
and then use that:
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>
并使用它:
An alternative is to pass in an IComparer<T>
and use that:
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)
这是您能够保证<运算符重载运算符是静态的,并且没有办法限制类型参数来需要它。
This is the closest you can get to guaranteeing a "<" operator - overloaded operators are static, and there's no way of constraining a type argument to require it.
这篇关于C#中的比较:运算符'<'不能应用于'T'和'T'类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!