Skip to main content
 首页 » 编程设计

C# 泛型 : Inserting T as the where T : IComparableT> interface conflict

2024年02月24日24zhoujg

这是对 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 接口(interface),因此

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>>'. 

请您参考如下方法:

您的实现非常困惑。在我看来这就足够了:

// replaces existing Evaluator signature.  I would personally ditch this 
// definition and just use Func<TValue, TKey> instead 
public delegate TKey Evaluator<TKey, TValue>(TValue item); 
 
class PriorityQueue<T> 
{ 
    Evaluator<int, T> Evaluate; 
    Heap<int, T> m_heap; 
 
    public PriorityQueue(Evaluator<int, T> evaluateFunction) 
    { 
        Evaluate = evaluateFunction; 
        m_heap = new Heap<int, T>(HeapType.MinHeap); 
    } 
 
    public void Insert(T element) 
    { 
        m_heap.Insert(Evaluate(element), element); 
    } 
} 

优先队列应该有一个通用键有什么原因吗?如果是这样,那么您应该指定 PriorityQueue<TKey, TValue>而是替换 int与 TKey , 添加 TKey : IComparable<TKey> 的约束(就像在您的堆签名中一样。)

基本上,如果您希望键是任何类型,您的优先级队列的定义应该看起来像堆的定义,或者相同但未在键类型上进行参数化。