Cannot apply Operator '<' to operands of type T and T

走远了吗. 提交于 2021-02-04 12:12:00

问题


so here's my code

public void BubbleSort<T>(T[] array) where T : IComparable<T>
{
    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 1; j < array.Length; j++)
        {
            if (array[j] < array[j - 1])
            {

            }
        }
    }
}

and before you shoot be down for not searching. I have searched and one of the answers here on SO said to use an icomparable interface to solve the problem.

unfortunately i am not going anywhere with this error.


回答1:


It looks like you're expecting the IComparable<T> constraint to allow you to use an inequality operator. IComparable and IComparable<T> say nothing about using inequality operators directly. Instead, what they do are provide a CompareTo() method you can use to simulate the inequality operators:

public void BubbleSort<T>(T[] array) where T: IComparable<T>
{
    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 1; j < array.Length; j++)
        {
            if (array[j].CompareTo(array[j-1]) < 0)
            {

            }
        }
    }
}



回答2:


If you can't add a generic constraint, then Comparer<T>:

var comparer = Comparer<T>.Default;

is very useful. You can then use comparer.Compare(x,y) (and check the result for negative, zero, positive); this supports types that implement IComparable<T> or IComparable, included "lifted" support for Nullable<T> wrappers - and will avoid boxing for the struct and Nullable<T> cases when the type supports IComparable<T>.




回答3:


You cannot use operators on generic types.

Instead, you need to use the CompareTo() method from IComparable<T>:

if (array[j].CompareTo(array[j - 1]) < 0)

Beware of nulls.




回答4:


Hence you declare T as IComparable, use its IComparable.CompareTo method :

 if (array[j].CompareTo(array[j-1]) < 0)
 {

 }


来源:https://stackoverflow.com/questions/19895125/cannot-apply-operator-to-operands-of-type-t-and-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!