C#——实现IComparableT 接口,ArrayLIst调用ArrayLIst.Sort()抛出System.InvalidOperationException异常解决方案
问题描述
未经处理的异常: System.InvalidOperationException: 未能比较数组中的两个元素。 ---> System.ArgumentException: 必须至少有 一个对象实现 IComparable。在 System.Collections.Comparer.Compare(Object a, Object b)在 System.Array.SorterObjectArray.InsertionSort(Int32 lo, Int32 hi)在 System.Array.SorterObjectArray.IntroSort(Int32 lo, Int32 hi, Int32 depthLimit)在 System.Array.SorterObjectArray.IntrospectiveSort(Int32 left, Int32 length)--- 内部异常堆栈跟踪的结尾 ---在 System.Array.SorterObjectArray.IntrospectiveSort(Int32 left, Int32 length)在 System.Array.Sort(Array keys, Array items, Int32 index, Int32 length, IComparer comparer)在 System.Collections.ArrayList.Sort(Int32 index, Int32 count, IComparer comparer)在 System.Collections.ArrayList.Sort()在 Homework.Program.Main(String[] args) 位置 E:\Code\Programs\C#\Homework\Program.cs:行号 201
官方文档
ArrayList 类(System.Collections.ArrayList):https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist?view=netframework-4.8
IComparable 接口:https://docs.microsoft.com/zh-cn/dotnet/api/system.icomparable?view=netframework-4.8
IComparable
问题分析
IComparable
ArrayLIst.Sort()方法只能对实现IComparable接口的类对象进行排序。
解决方案
使用非泛型的Comparable接口替换泛型的Comparable
class Circle : Ellipse, IComparable
public int CompareTo(Object other){return this.Radius.CompareTo(((Circle)other).Radius);}
参考文章
https://blog.csdn.net/weixin_43272781/article/details/105292114
https://blog.csdn.net/Maybe_ch/article/details/81359408
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
