我正在尝试对 <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;
}
}
}
}
最佳答案
如果除了默认比较之外你不需要任何东西,你可以使用:
// 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)
{
...
}
}
或者允许自定义比较:
public static void BubbleSort<T>(this List<T> array, IComparer<T> comparer)
{
...
if (comparer.Compare(array[j - 1], array[j]) > 0)
{
...
}
}
或者限制T
实现 IComparable<T>
的类型:
public static void BubbleSort<T>(this List<T> array) where T : IComparable<T>
{
...
if (array[j - 1].CompareTo(array[j]) > 0)
{
...
}
}
请注意,在 T
上添加约束这里意味着任何调用者需要知道他们使用的类型参数需要实现IComparable<T>
...它使它在编译时更安全,代价是将约束传播到调用链中。 (一种选择是允许没有比较器的受限版本和有比较器的无约束版本。)
关于c# - 对类型为 T 的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993664/