gpt4 book ai didi

c# - 泛型和 IComparable - 错误 CS00301

转载 作者:行者123 更新时间:2023-12-02 04:56:05 28 4
gpt4 key购买 nike

我尝试开发一个实现 IComparable 的通用类“MinHeap(T)”。当泛型是“int”或另一个类“Code”时,它工作正常。更进一步,为 T 使用通用类“Node(Code)”导致下面提到的错误。

我可能太新了,不了解 IComparable 和 IComparable(T) 之间的细微差别。有人有想法吗?在此先感谢您的帮助,陆杰

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com