问题 如何编写嵌套泛型函数


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

方式 T 不能用作类型参数 T 在泛型中   或方法 Heap.MainClass.MaxHeapify<T>(T[], int, int)。没有   拳击或类型参数转换 T 至    System.IComparable<T> (CS0314)(HeapSort)


12155
2018-01-30 06:48


起源



答案:


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

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

你在上面指定了这个约束 MaxHeapify 方法并且为了调用它,T必须满足这个条件。


10
2018-01-30 06:51



是的,发现。谢谢! - Nemo


答案:


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

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

你在上面指定了这个约束 MaxHeapify 方法并且为了调用它,T必须满足这个条件。


10
2018-01-30 06:51



是的,发现。谢谢! - Nemo


MaxHeapify<T>() 方法有一个通用约束 where T : IComparable 但是你的 HeapSort<T>() 方法没有它,因此编译器无法从HeapSort方法解析对MaxHeapify的调用。 您应该添加一个通用约束 where : IComparable 到你的 HeapSort<T>() 方法也。

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

1
2018-01-30 06:54