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<T> 接口:https://docs.microsoft.com/zh-cn/dotnet/api/system.icomparable-1?view=netframework-4.8
問題分析
IComparable<T> 接口不適用于ArrayLIst。
ArrayLIst.Sort()方法只能對實現IComparable接口的類對象進行排序。
解決方案
使用非泛型的Comparable接口替換泛型的Comparable<T> 接口。
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
總結
以上是生活随笔為你收集整理的C#——实现IComparableT 接口,ArrayLIst调用ArrayLIst.Sort()抛出System.InvalidOperationException异常解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#——Ellipse(椭圆)类[继承C
- 下一篇: Spring MVC——POST请求ap