【问题标题】:How do I implement IComparable<T>?如何实现 IComparable<T>?
【发布时间】: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&lt;T&gt; where T : IComparable。您希望 T 具有可比性,而不是列表。
  • 检查这个问题的答案是否对您有帮助:C# Interfaces - How to Implement IComparable?

标签: c# generics comparison icomparable icomparablet


【解决方案1】:

实现这一点的一种方法是要求列表中的元素具有可比性,即让它们实现IComparable 接口。您可以使用T 上的泛型类型约束来表达这一点,如下所示:

public class SortedSinglyLinkedList<T> : where T : IComparable 

执行此操作的更通用方法,也允许您的列表包含未实现此 IComparable 接口的元素,是遵循许多 c# BCL 通用集合类中使用的策略(例如 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));

【讨论】:

  • @Alan_UK,不客气。我刚刚编辑了我的答案,包括指向 BCL 排序字典和排序列表实现的链接,这样你就可以亲眼看到它们是如何使用它的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多