使用泛型扩展接口的类

时间:2017-12-21 21:39:56

标签: c# generics interface

所以我正在滚动自己的最大堆,而且我使用扩展接口的泛型类做错了。说我有这样的课程:

class SuffixOverlap:IComparable<SuffixOverlap>
{
    //other code for the class
     public int CompareTo(SuffixOverlap other)
    {
        return SomeProperty.CompareTo(other.SomeProperty);
    }
}

然后我创建了我的堆类:

class LiteHeap<T> where T:IComparable
{
    T[] HeapArray;
    int HeapSize = 0;
    public LiteHeap(List<T> vals)
    {
        HeapArray = new T[vals.Count()];
        foreach(var val in vals)
        {
            insert(val);
        }
    }

    //the usual max heap methods
}

但是当我尝试这样做时:

LiteHeap<SuffixOverlap> olHeap = new LiteHeap<SuffixOverlap>(listOfSuffixOverlaps);

我收到错误: The type SuffixOverlap cannot be used as a type parameter T in the generic type or method LiteHeap<T>. There is no implicit reference conversion from SuffixOverlap to System.IComparable.

如何创建LiteHeap作为使用通用类T实现IComparable的类,这样我就可以编写new LiteHeap<SomeClass>,它可以在SomeClass实现IComparable的地方工作

1 个答案:

答案 0 :(得分:5)

IComparableIComparable<T>是不同的,完全无关的接口。

您需要将其更改为where T : IComparable<T>,以便它与您的班级实际匹配。