C# 如何实现IComparable<;T>;?
我已经创建了自己的通用Java数据结构库,现在我在C#中创建它,但我一直在尝试实现CompareTo方法来对单个链表进行排序。 这是我的密码:C# 如何实现IComparable<;T>;?,c#,generics,comparison,icomparable,icomparablet,C#,Generics,Comparison,Icomparable,Icomparablet,我已经创建了自己的通用Java数据结构库,现在我在C#中创建它,但我一直在尝试实现CompareTo方法来对单个链表进行排序。 这是我的密码: class SortedSinglyLinkedList<T> : IComparable // my class // [irrelevant stuff...] // Sorts the list, from the least to the greatest element public void sort() {
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 SortedSingleyLinkedList:IComparable//my class
//[无关的东西…]
//从最小元素到最大元素对列表进行排序
公共无效排序()
{
for(int i=0;i“T”不包含“CompareTo”的定义,并且找不到接受类型为“T”的第一个参数的扩展方法“CompareTo”(是否缺少using指令或程序集引用?)
{
move(i,j);//此方法仅将节点从i移动到j
}
}
}
}
//比较两个元素
int i可比较。比较到(T其他)
{
//我应该在这里放些什么来让它工作?
}
实现这一点的一种方法是要求列表中的元素具有可比性,即让它们实现接口。您可以使用T
上的泛型类型约束来表示这一点,如下所示:
public class SortedSinglyLinkedList<T> : where T : IComparable
在Sort
方法中,使用此比较器实例执行比较:
_comparer.Compare(get(i), get(j));
我想你的意思是
分类单链接列表,其中T:I可比较
。您希望T
具有可比性,而不是列表。请检查此问题的答案是否有助于您:@Alan_UK,欢迎您。我刚刚编辑了我的答案,添加了指向BCL排序字典和排序列表实现的链接,这样您就可以亲眼看到它们是如何利用这些功能的。
_comparer.Compare(get(i), get(j));