我已经创建了自己的通用Java数据结构库,现在正在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?
}
最佳答案
实现此目的的一种方法是,要求列表中的元素具有可比性,即让它们实现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));
关于c# - 如何实现IComparable <T>?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30552655/