如何编写嵌套泛型函数

时间:2012-01-30 06:48:08

标签: c#

我正在尝试编写一个通用的堆排序算法。我收到以下错误。可能是什么原因?

  

类型T不能用作泛型类型中的类型参数T   或方法Heap.MainClass.MaxHeapify<T>(T[], int, int)。没有   装箱或类型参数从T转换为   System.IComparable<T>(CS0314)(HeapSort)

2 个答案:

答案 0 :(得分:10)

您需要指定T必须在IComparable<T>函数上实现HeapSort的相同通用约束:

private static void HeapSort<T>(T[] items) where T : IComparable<T>

您在MaxHeapify方法上指定了此约束,为了调用它,T必须满足此条件。

答案 1 :(得分:1)

MaxHeapify<T>()方法的通用约束为where T : IComparable,但您的HeapSort<T>()方法没有它,因此编译器无法从HeapSort方法解析对MaxHeapify的调用。 您还应该在where : IComparable方法中添加HeapSort<T>()的通用约束。

private static void HeapSort<T>(T[] items) where T : IComparable<T>