我正在尝试<T>
使用冒泡排序对类型列表进行排序.不幸的是我在比较未知类型的对象时遇到了问题.
到目前为止我尝试过的:
public static void BubbleSort<T>(this List<T> array)
{
for (int i = (array.Count - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (array[j - 1] > array[j]) // issue here
{
var temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
如果您不需要除默认比较之外的任何其他内容,则可以使用:
// TODO: Rename the parameter...
public static void BubbleSort<T>(this List<T> array)
{
IComparer<T> comparer = Comparer<T>.Default;
...
if (comparer.Compare(array[j - 1], array[j]) > 0)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
或者允许自定义比较:
public static void BubbleSort<T>(this List<T> array, IComparer<T> comparer)
{
...
if (comparer.Compare(array[j - 1], array[j]) > 0)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
或者限制T
实现的类型IComparable<T>
:
public static void BubbleSort<T>(this List<T> array) where T : IComparable<T>
{
...
if (array[j - 1].CompareTo(array[j]) > 0)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在T
此处添加约束意味着任何调用者都需要知道他们使用的类型参数需要实现IComparable<T>
...它使编译时更安全,代价是在调用链上向上传播约束.(一种选择是允许没有比较器的受约束版本和带有比较器的无约束版本.)
不,你无法比较2个T
值>
.
首先,您需要添加约束T
:
public static void BubbleSort<T>(this List<T> array)
where T : IComparable<T>
{
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话
//if (array[j - 1] > array[j]) // issue here
if (array[j - 1].CompareTo(array[j]) > 0) // solved
Run Code Online (Sandbox Code Playgroud)