C# 实现IComparable<;T>;用于比较类型T的泛型类的接口

C# 实现IComparable<;T>;用于比较类型T的泛型类的接口,c#,.net,linq,generics,icomparable,C#,.net,Linq,Generics,Icomparable,我尝试在泛型类中使用IComparable来比较T类型的元素,结果出现以下错误: 运算符“出现此错误的原因是不能将不等式运算符(“”)与IComparable一起使用,除非重写它们 您可以改用CompareTo() public类Mystack:IComparable其中T:IComparable { 公共T[]堆栈=新T[2]; 公共int比较(Mystack其他) { //如果当前堆栈其他堆栈返回+1 //如果当前堆栈项==其他堆栈项返回0 用于(无功电流=0;电流

我尝试在泛型类中使用
IComparable
来比较T类型的元素,结果出现以下错误:


运算符“出现此错误的原因是不能将不等式运算符(“”)与IComparable一起使用,除非重写它们

您可以改用CompareTo()

public类Mystack:IComparable其中T:IComparable
{
公共T[]堆栈=新T[2];
公共int比较(Mystack其他)
{
//如果当前堆栈<其他堆栈返回-1
//如果当前堆栈>其他堆栈返回+1
//如果当前堆栈项==其他堆栈项返回0
用于(无功电流=0;电流<2;电流++)
{
if(stack[current].CompareTo(other.stack[current])<0)
{
返回-1;
}
else if(stack[current].CompareTo(other.stack[current])>0)
{
返回1;
}
}
返回0;
}
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;
    }
}
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;
    }
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;
}