我觉得很奇怪,C#让我调用类的排序功能,却不需要指定排序方式或编写比较重载函数。当我运行这段代码时,出现了错误。
List<MyClass> myClassArray= new List<MyClass>();
//myClassArray.add(...);
myClassArray.Sort();
An unhandled exception of type System.InvalidOperationException occurred in mscorlib.dll
Additional information: Failed to compare two elements in the array.
Why does C# let me compile this code when it doesnt know how to sort this! -edit-
Codex问为什么要这样做。我在我的评论中写了一份理论。这里是一些示例代码。
class A : IComparable<A>
{
public int CompareTo(A a) { return 0; }
}
class C //: IComparable<A>
{
public int CompareTo(A a) { return 0; }
}
static void test()
{
A a = new A();
bool b;
C c = new C();
object o = a;
IComparable<A> ia = (IComparable<A>)o;
b = ia == ia;
o = c;
IComparable<A> ic = (IComparable<A>)o;
b = ic == ic;
//uncomment this to get a compile time error
//IComparable<A> ic2 = c;
return;
}
如果你在返回之前取消注释该行,你会得到一个编译时错误。当你在类c中取消注释IComparable时,它将编译并工作。