通用方法不支持约束

Cha*_*aru 1 c# generics

我正在尝试编写一个泛型方法,它应该支持ex int,double,float等的内部类型.该方法是对数组进行排序.我得到一个编译时错误,说"我不能应用运算符<到类型T",但我该如何解决呢?我应该使类通用并使用约束吗?这是我的代码:

public static T[] Sort<T>(T[] inputArray) 
{
    for (int i = 1; i < inputArray.Length; i++)
    {
        for (int j = i - 1; j >= 0; j--)
        {
            ***if (inputArray[j + 1] < inputArray[j])***
            {
                T temp = inputArray[j + 1];
                inputArray[j + 1] = inputArray[j];
                inputArray[j] = temp;
            }
            else
            {
                break;
            }
        }
    }
    return inputArray;
}
Run Code Online (Sandbox Code Playgroud)

p.s*_*w.g 5

C#不支持对类型支持的运算符的通用约束.但是,.NET提供了许多提供类似功能的接口.在这种情况下,您需要添加通用约束以确保T实现IComparable<T>.

public static T[] Sort<T>(T[] inputArray) where T : IComparable<T>
{
    for (int i = 1; i < inputArray.Length; i++)
    {
        for (int j = i - 1; j >= 0; j--)
        {
            if (inputArray[j + 1].CompareTo(inputArray[j]) < 0)
            {
                T temp = inputArray[j + 1];
                inputArray[j + 1] = inputArray[j];
                inputArray[j] = temp;
            }
            else
            {
                break;
            }
        }
    }
    return inputArray;
}
Run Code Online (Sandbox Code Playgroud)