使用泛型扩展接口的类

jim*_*web 0 c# generics interface

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

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

然后我创建我的堆类:

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
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这样做时:

LiteHeap<SuffixOverlap> olHeap = new LiteHeap<SuffixOverlap>(listOfSuffixOverlaps);
Run Code Online (Sandbox Code Playgroud)

我收到错误: 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的地方工作

SLa*_*aks 5

IComparable并且IComparable<T>是不同的,完全不相关的接口.

您需要将其更改为where T : IComparable<T>,以便它实际匹配您的类.

  • ...或者让类实现`IComparable`和`IComparable <SuffixOverlap>`并实现它,就像处理`IEnumerable`和`IEnumerable <T>`的实现一样. (2认同)