我正在尝试编写一种通用方法,该方法应支持Ex Int,Double,Float等的固有类型。该方法正在对数组进行排序。我遇到了一个编译时间错误,说"不能应用运算符< type t;我理解的t type 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;
}
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;
}
没有一个通用约束,您可以应用将类型限制在 <
运算符的人中。
您可以做的最好的是将类型限制在实现IComparable<T>
或接受类型IComparer<T>
的参数进行比较的类型中(有两种方法,一种使用每个选项,也值得这样做)。