14

所以这是我的代码

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

            }
        }
    }
}

在你拍摄之前因为没有搜索而被击落。我已经搜索过,其中一个关于 SO 的答案说使用无与伦比的界面来解决问题。

不幸的是,我不会因为这个错误而去任何地方。

4

4 回答 4

20

看起来您希望IComparable<T>约束允许您使用不等式运算符。IComparable并且IComparable<T>什么也不说直接使用不等式运算符。相反,他们所做的是提供一种CompareTo()可用于模拟不等式运算符的方法:

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

            }
        }
    }
}
于 2013-11-10T21:02:06.587 回答
12

如果您无法添加通用约束,则Comparer<T>

var comparer = Comparer<T>.Default;

非常有用。然后您可以使用comparer.Compare(x,y)(并检查结果是否为负、零、正);这支持实现IComparable<T>IComparable包含对包装器的“提升”支持的类型Nullable<T>- 并且将避免Nullable<T>在类型支持时对结构和情况进行装箱IComparable<T>

于 2013-11-10T21:08:08.157 回答
6

您不能对泛型类型使用运算符。

相反,您需要使用以下CompareTo()方法IComparable<T>

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

小心nulls。

于 2013-11-10T21:02:04.177 回答
3

因此,您声明TIComparable,使用其IComparable.CompareTo方法:

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

 }
于 2013-11-10T21:02:31.763 回答