无法应用运算符'<'转换为T和T类型的操作数 [英] Cannot apply Operator '<' to operands of type T and T

查看:46
本文介绍了无法应用运算符'<'转换为T和T类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

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.

推荐答案

您似乎期望 IComparable< T> 约束允许您使用不等式运算符. IComparable IComparable< T> 对直接使用不等式运算符一无所获.相反,它们的作用是提供一个 CompareTo()方法,可用于模拟不等式运算符:

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)
            {

            }
        }
    }
}

这篇关于无法应用运算符'&lt;'转换为T和T类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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