【发布时间】:2015-05-31 00:25:50
【问题描述】:
我已经创建了自己的通用 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?
}
【问题讨论】:
-
我想你的意思是
class SortedSinglyLinkedList<T> where T : IComparable。您希望T具有可比性,而不是列表。 -
检查这个问题的答案是否对您有帮助:C# Interfaces - How to Implement IComparable?
标签: c# generics comparison icomparable icomparablet