为通用类实现IComparable <t>接口以比较类型T

时间:2018-03-24 22:15:12

标签: c# .net linq generics icomparable

我尝试在泛型类中使用IComparable<T>来比较类型T的元素,我得到以下错误:

  

“运营商”&lt;'不能应用于'T'和'T'类型的操作数

我想知道是否可以解决这个问题。 这是一个简单的例子IComparable<T>在我定义我的类时采用int:

public class IntStack : IComparable<IntStack>
{
    public int[] stack = new int[2];

    public int CompareTo(IntStack other)
    {
        // If the current stack < other stack return -1
        // If the current stack > other stack return +1
        // If current stack entries == other stack entries return 0
        for (var current = 0; current < 2; current++)
        {
            if (stack[current] < other.stack[current])
            {
                return -1;
            }
            else if (stack[current] > other.stack[current])
            {
                return 1;
            }
        }
        return 0;
    }
}
当我将上面的类更改为泛型时,

IComparable<T>现在不能在这里工作:

public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
    public T[] stack = new T[2];

    public int CompareTo(Mystack<T> other)
    {
        // If the current stack < other stack return -1
        // If the current stack > other stack return +1
        // If current stack entries == other stack entries return 0
        for (var current = 0; current < 2; current++)
        {
            if (stack[current] < other.stack[current])
            {
                return -1;
            }
            else if (stack[current] > other.stack[current])
            {
                return 1;
            }
        }
        return 0;
    }

1 个答案:

答案 0 :(得分:2)

您收到此错误的原因是您不能将不等号运算符(&#34;&lt;&#34;,&#34;&gt;&#34;)与IComparable一起使用,除非您覆盖它们。< / p>

您可以改用CompareTo()。

public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
public T[] stack = new T[2];

public int CompareTo(Mystack<T> other)
{
    // If the current stack < other stack return -1
    // If the current stack > other stack return +1
    // If current stack entries == other stack entries return 0
    for (var current = 0; current < 2; current++)
    {
        if (stack[current].CompareTo(other.stack[current]) < 0)
        {
            return -1;
        }
        else if (stack[current].CompareTo(other.stack[current]) > 0)
        {
            return 1;
        }
    }
    return 0;
}
相关问题