没有实现IComparable,Sort函数为什么是编译时不检查错误,而是运行时检查错误?
泛型的List在编译时已经知道了里面的对象的类型了,所以如果该类不支持IComparable接口,那么是不是应该不让Sort函数的调用编译通过呢?
但是我做了一个实验,发现,Sort函数的调用总是能通过的,而是否支持了IComparable接口,是在运行时检查的。
下面的程序,编译可以通过,运行时报错:
class student
{
public int age;
public string name;
}
class Program
{
static void Main(string[] args)
{
List<student> a = new List<student>();
a.Add(new student() { age = 10, name = "abc" });
a.Add(new student() { age = 11, name = "xyz" });
a.Sort();
}
}
Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
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.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
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)
--- End of inner exception stack trace ---
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 ConsoleApplication1.Program.Main(String[] args) in d:\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 54
------------------------------------------------------------------------------------
奇怪了,为什么编译时不检查呢,既然student没有继承和实现IComparable,那么Sort函数应该编译不过才对啊,必须要等到运行时来动态检查吗?
------解决方案--------------------你调用的是List的无参数的sort接口,当然不会在编译时检查了