在C#中的问题比较 [英] Comparision problem in C#

查看:260
本文介绍了在C#中的问题比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 BinaryTreeNode< T> 类,然后创建 添加(T数据) 对于 二叉树<方法; 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'

实例操作数:

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

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

我是C#小白和使用VS08 Express版本。请帮忙

I'm C# noob and using VS08 Express Edition. Please help.

推荐答案

您应该添加一个约束,使得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#中的问题比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆