我有一個TestClass<T>將演變?yōu)榛诙训膬?yōu)先級隊列。堆是List<T>類型。我正在重新排序代碼,因此需要比較的元素List<T>。你可以猜到我收到了 error CS0019: Operator < cannot be applied to operands of type T and T。我知道這并不奇怪,并且C#泛型不是C ++模板。所以,我試圖約束Type T帶IComparable。但這并沒有幫助。我發(fā)現(xiàn)的建議(為了解決此問題)主要是創(chuàng)建一個虛擬類,該類定義了此類運算符,并限制了T此類。但是,我發(fā)現(xiàn)此解決方案不是很方便。那么,還有其他方法可以解決此問題嗎?這是相關的代碼:using System;using System.Collections.Generic;public class TestClass<T> where T : IComparable{ private List<T> heap; public TestClass(int maxSize) { this.heap = new List<T>(maxSize + 1); } private void ReorderUpwards(int nodeIndex) { while (nodeIndex > 1 && this.heap[nodeIndex / 2] < this.heap[nodeIndex]) { nodeIndex /= 2; } }}
比較通用列表的元素
慕桂英3389331
2021-04-13 17:14:58