我试图开发一个实现 IComparable 的通用类“MinHeap(T)”。当泛型为“int”或其他类“代码”时,它可以正常工作。更进一步并为 T 使用泛型类“Node(Code)”会导致下面提到的错误。
我可能太新了,不了解 IComparable 和 IComparable(T) 之间的细微差别。有人有想法吗?提前感谢您的帮助,LJ
public class MinHeap<T> where T : IComparable
{
...
}
public class Node<T> where T : IComparable
{
T data
...
public int CompareTo(object obj)
{
Node<T> otherNode = obj as Node<T>;
return this.data.CompareTo(otherNode.data);
}
...
}
public class Code : IComparable
{
public int freq;
...
public int CompareTo(object obj)
{
Code otherCode = obj as Code;
return this.freq.CompareTo(otherCode.freq);
}
}
static void Main(string[] args)
{
MinHeap<int> hInt = new MaxHeap<int>(heapSeed); // works fine
MinHeap<Code> hCode = new MinHeap<Code>(codeList); // works fine
...
Node<Code>[] nodeCodeList = new Node<Code>[freqList.Length]; // ok
MinHeap<Node<Code>> h = new MinHeap<Node<Code>>(nodeCodeList); // Error
...
}
错误信息:
错误 2 类型“Algorithms.Node(Algorithms.Code)”不能用作泛型类型或方法“Algorithms.MinHeap(T)”中的类型参数“T”。没有从“Algorithms.Node(Algorithms.Code)”到“System.IComparable”的隐式引用转换。