我在玩,看看如果我创建List
个不实现比较运算符并调用.Sort()
的对象,我会得到什么编译器错误。 我很惊讶它编译然后在运行时崩溃:
[System.ArgumentException: At least one object must implement IComparable.]
at System.Collections.Comparer.Compare(Object a, Object b)
at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y)
at System.Collections.Generic.ArraySortHelper`1.InsertionSort(T[] keys, Int32 lo, Int32 hi, IComparer`1 comparer)
at System.Collections.Generic.ArraySortHelper`1.IntroSort(T[] keys, Int32 lo, Int32 hi, Int32 depthLimit, IComparer`1 comparer)
at System.Collections.Generic.ArraySortHelper`1.IntrospectiveSort(T[] keys, Int32 left, Int32 length, IComparer`1 comparer)
at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
[System.InvalidOperationException: Failed to compare two elements in the array.]
at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
at System.Collections.Generic.List`1.Sort()
at Example.Main() :line 49
C# 编译器允许编译此代码的原因是什么?
注意:我希望很明显,我不是在问如何修复我的代码,这是微不足道的,我是在问为什么编译这个有缺陷的代码。
您可以通过实现IComparer
接口来提供自编写的比较器。当你不这样做时,它会寻找Comparer<T>.Default
来得到一个。因此,从技术上讲,在对象未实现Icomparable
的列表上调用Sort()
是可以的,因为届时将使用Comparer<T>.Default
。这意味着您可以在任何列表上调用Sort()
,而不受值必须实现IComparable
的限制。但这也意味着您无法在编译时检查在Sort()
源代码内部使用时Comparer<T>.Default
是否有可用的比较器。