c# – 使用类型T对List进行排序
发布时间:2020-12-15 20:01:01 所属栏目:百科 来源:网络整理
导读:我正在尝试对类型列表 T进行排序与泡沫排序.不幸的是我在比较未知类型的对象时遇到了问题. 到目前为止我尝试过的: public static void BubbleSortT(this ListT array){ for (int i = (array.Count - 1); i = 0; i--) { for (int j = 1; j = i; j++) { if (a
我正在尝试对类型列表< T>进行排序与泡沫排序.不幸的是我在比较未知类型的对象时遇到了问题.
到目前为止我尝试过的: public static void BubbleSort<T>(this List<T> array) { for (int i = (array.Count - 1); i >= 0; i--) { for (int j = 1; j <= i; j++) { if (array[j - 1] > array[j]) // issue here { var temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } } 解决方法
如果您不需要除默认比较之外的任何其他内容,则可以使用:
// TODO: Rename the parameter... public static void BubbleSort<T>(this List<T> array) { IComparer<T> comparer = Comparer<T>.Default; ... if (comparer.Compare(array[j - 1],array[j]) > 0) { ... } } 或者允许自定义比较: public static void BubbleSort<T>(this List<T> array,IComparer<T> comparer) { ... if (comparer.Compare(array[j - 1],array[j]) > 0) { ... } } 或者将T限制为实现IComparable< T>的类型: public static void BubbleSort<T>(this List<T> array) where T : IComparable<T> { ... if (array[j - 1].CompareTo(array[j]) > 0) { ... } } 注意,在这里添加约束意味着任何调用者都需要知道他们使用的类型参数需要实现IComparable< T> …它使编译时更安全,代价是传播的约束呼叫链. (一种选择是允许没有比较器的受约束版本和带有比较器的无约束版本.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Ajax的技术原理
- JSON.parse()和JSON.stringify()
- ruby – 什么是Rack – “no acceptor”错误?
- Basics of Template Monster's Flash Site: data stora
- For oracle databases, if the top showing the oracle dat
- 如何在debian 6中安装ruby 2.0?
- ruby-on-rails – 通过与其他属性关联,为has_many创建Rails
- react-native – React Native Password TextInput抛出警告
- flashbuilder4.5 作为eclipse插件
- XML-ABAP处理