gpt4 book ai didi

c# - 如何实现 IComparable

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:09 25 4
gpt4 key购买 nike

我已经创建了我自己的通用 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 

一种更通用的方法是遵循许多 c# BCL 泛型集合类中使用的策略,它还允许您的列表包含未实现此 IComparable 接口(interface)的元素(例如 SortedDictionarySortedList ):使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com