c# - 泛型和 IComparable - 错误 CS00301

标签 c# .net generics icomparable

我尝试开发一个实现 IComparable 的泛型类“MinHeap(T)”。当泛型为“int”或另一个类“Code”时,它工作正常。更进一步,为 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
...
}

错误消息:

Error 2 The type 'Algorithms.Node(Algorithms.Code)' cannot be used as type parameter 'T' in the generic type or method 'Algorithms.MinHeap(T)'. There is no implicit reference conversion from 'Algorithms.Node(Algorithms.Code)' to 'System.IComparable'.

最佳答案

类(class)Node<T>不实现IComparable 。它只是对 T 的类型有一个约束。 .

看来您已尝试实现 decorator图案。也实现接口(interface),然后将方法映射到装饰对象。

关于c# - 泛型和 IComparable - 错误 CS00301,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947719/

相关文章:

java - 不明白 <T> 和 <?> 的一些内容

c# - 如何使用clearcanvas访问DICOM序列的所有内容

c# - 如何在 Unity 中使用 UI.Text 作为预制件?

c# - 多线程加载xml文件到内存

c# - 为什么 IList<T> 不只从 ICollection<T> 继承?

c# - C# 中的通用接口(interface)是否可以防止装箱? (.NET 与单声道性能)

c# - 在 C# 中模拟局部变量

.net - DefaultConnectionLimit 的最大值

.net - dynamic-linq Select 中的字符串连接

java - java中静态通用接口(interface)的替代方案