我已经创建了我自己的通用库,现在我正在C#中创建它,但是我不得不尝试实现CompareTo方法来排序一个单一链接的列表。这是我的密码:
class SortedSinglyLinkedList<T> : IComparable // my class
// [irrelevant stuff...]
// Sorts the list, from the least to the greatest element
public void sort()
{
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (get(i).CompareTo(get(j)) < 0) // ERROR -> 'T' does not contain a definition for 'CompareTo' and no extension method 'CompareTo' accepting a first argument of type'T' could be found (are you missing a using directive or an assembly reference?)
{
move(i, j); // this method simply moves a node from i to j
}
}
}
}
// Compares 2 elements
int IComparable<T>.CompareTo(T other)
{
// what should I put here to make it work?
}发布于 2015-05-31 00:40:11
实现这一目标的一种方法是要求列表中的元素具有可比性,即让它们实现IComparable接口。您可以在T上使用泛型类型约束来表示这一点,如下所示:
public class SortedSinglyLinkedList<T> : where T : IComparable 这样做的一个更一般的方法,也允许列表包含不实现此IComparable接口的元素,是遵循许多c# BCL泛型集合类(例如SortedDictionary或SortedList)中使用的策略:使用IComparer实例来执行比较。
public class SortedSinglyLinkedList<T>
{
private readonly IComparer<T> _comparer;
// ...
public SortedSinglyLinkedList()
{
_comparer = Comparer<T>.Default; // use the default.
// ...
}
public SortedSinglyLinkedList(IComparer<T> comparer)
{
_comparer = comparer ?? Comparer<T>.Default;
// ...
}
}在您的Sort方法中,使用这个比较实例来执行比较:
_comparer.Compare(get(i), get(j));https://stackoverflow.com/questions/30552655
复制相似问题