为什么C#让我在不知道如何排序时编译排序代码

2 c# sorting

我认为C#允许我在我的类上调用sort并且没有指定对它们进行排序的方法,也没有编写比较重载这是奇怪的.当我运行此代码时,会弹出此错误

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.
Run Code Online (Sandbox Code Playgroud)

为什么C#让我在不知道如何排序时编译这段代码!-编辑-

食典委问为什么会这样做.我在评论中写了一个关于它为什么会这样做的理论.这里有一些示例代码.

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;
    }
Run Code Online (Sandbox Code Playgroud)

如果在返回之前取消注释该行,则会出现编译时错误.当您在类c中取消注释IComparable时,它将编译并工作.

Mat*_*att 13

List <T>的泛型参数没有约束,要求它实现IComparable <T>.如果有的话,它会(某种程度上)保证元素可以被排序,但你不能使用List <T>来保存任何没有实现IComparable的东西.由于您可能不会对您创建的每个列表进行排序,因此这是正确的决定.