这对 C# 泛型/设计模式大师来说是一个挑战。
我正在尝试实现一个通用堆,然后是一个使用该堆的优先级队列。
我的堆的签名是:
class Heap<TKey, TValue> where TKey : IComparable<TKey>
我的优先队列类是:
public delegate IComparable<T> Evaluator<T>(T item);
class PriorityQueue<T> : IQueue<T>
{
Evaluator<T> Evaluate;
Heap<IComparable<T>, T> m_heap;
public PriorityQueue(Evaluator<T> evaluateFunction)
{
Evaluate = evaluateFunction;
m_heap = new Heap<int, T>(HeapType.MinHeap);
}
...
public void Insert(T element)
{
m_heap.Insert(Evaluate(element), element);
}
...
但是这样做时,编译器(有理由)抱怨 ICompareble 没有实现 ICompareble 接口,因此
Heap<IComparable<T>, T> m_heap;
与冲突
where TKey : IComparable<TKey>
你能做些什么来解决这个问题?!
完整的编译器错误:
The type 'System.IComparable<T>' cannot be used as type parameter 'TKey' in the generic type or method 'Heap<TKey,TValue>'. There is no implicit reference conversion from 'System.IComparable<T>' to 'System.IComparable<System.IComparable<T>>'.