首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现IComparable<T>?

如何实现IComparable<T>?
EN

Stack Overflow用户
提问于 2015-05-31 00:25:50
回答 1查看 1.7K关注 0票数 1

我已经创建了我自己的通用库,现在我正在C#中创建它,但是我不得不尝试实现CompareTo方法来排序一个单一链接的列表。这是我的密码:

代码语言:javascript
复制
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?
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-31 00:40:11

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

代码语言:javascript
复制
public class SortedSinglyLinkedList<T> : where T : IComparable 

这样做的一个更一般的方法,也允许列表包含不实现此IComparable接口的元素,是遵循许多c# BCL泛型集合类(例如SortedDictionarySortedList)中使用的策略:使用IComparer实例来执行比较。

代码语言:javascript
复制
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方法中,使用这个比较实例来执行比较:

代码语言:javascript
复制
_comparer.Compare(get(i), get(j));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30552655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档