【问题标题】:Implementing IComparable<T> Interface for a generic class to compare type T为泛型类实现 IComparable<T> 接口以比较类型 T
【发布时间】:2018-03-24 22:15:12
【问题描述】:

我尝试在泛型类中使用 IComparable&lt;T&gt; 来比较 T 类型的元素,但出现以下错误:

“运算符'

我想知道是否可以解决这个问题。 这是一个简单的示例,当我将我的类定义为采用 int 时,IComparable&lt;T&gt; 正在工作:

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&lt;T&gt; 现在在我将上面的类更改为泛型时在这里不起作用:

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;
    }

【问题讨论】:

    标签: c# .net linq generics icomparable


    【解决方案1】:

    您收到此错误的原因是您不能在 IComparable 中使用不等式运算符(“”),除非您覆盖它们。

    您可以改用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多