[英]List.Sort() throws An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll - C#
I have a Person type list and it has some items and I want to sort this list by default(without any params). 我有一个Person类型列表,它有一些项目,并且我想默认对列表进行排序(没有任何参数)。 So I have used person.Sort() method.
所以我用了person.Sort()方法。 When I execute the code I get an exception writes
当我执行代码时,我得到一个异常写
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
mscorlib.dll中发生了类型为'System.InvalidOperationException'的未处理异常
at Sort() method. 在Sort()方法中。 Any experts please explain the reason behind.
任何专家请解释背后的原因。
List<Person> person = new List<Person>();
person.Add(new Person() { Name = "crank arm", Age = 1234 });
person.Add(new Person() { Name = "chain ring", Age = 1334 });
person.Add(new Person() { Name = "regular seat", Age = 1434 });
person.Add(new Person() { Name = "banana seat", Age = 1444 });
person.Sort();
You need to make your Person
class implement IComparable
您需要使您的
Person
类实现IComparable
The sort methods throws that exception when 排序方法在以下情况时抛出该异常
The default comparer Comparer.Default cannot find an implementation of the IComparable generic interface or the IComparable interface for type T.
默认的比较器Comparer.Default找不到类型T的IComparable通用接口或IComparable接口的实现。
Person是您定义的类,Sort方法不知道如何在Person对象之间进行比较,您需要实现比较方法,您可以参考: http : //msdn.microsoft.com/zh-cn/library/3da4abas(v = vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.