gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:54:29 26 4
gpt4 key购买 nike

我认为 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.

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

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;
}

如果在 return 之前取消注释该行,则会出现编译时错误。当您在类 c 中取消注释 IComparable 时,它​​将编译并运行。

最佳答案

List 的泛型参数没有要求它实现 IComparable 的约束。如果存在,它将(某种程度上)保证元素可以排序,但您将无法使用 List 来保存任何未实现 IComparable 的内容。由于您可能不会对创建的每个列表进行排序,因此这是正确的决定。

关于c# - 为什么 C# 在不知道如何排序时让我编译排序代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/633511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com