@H_301_1@我有一个网页,其中有一种我必须通过中文笔划订购列表.
我创建了一个包含如下代码的应用程序:
List<Student> stuList = new List<Student>() { new Student("上海"),new Student("深圳"),new Student("广州"),new Student("香港") }; System.Globalization.CultureInfo strokCi = new System.Globalization.CultureInfo("zh-tw"); System.Threading.Thread.CurrentThread.CurrentCulture = strokCi; ; //stuList.sort();
但是有一个错误:至少有一个对象必须实现IComparable.
这是什么意思,我该如何解决?
解决方法
您需要让您的Student类实现IComparable接口.这需要实现一个方法CompareTo,它可以简单地返回在您尝试排序的字符串之间调用CompareTo的结果.
public class Student : IComparable { private string name; public Student(string name) { this.name = name; } public int CompareTo(object other) { Student s = other as Student; if (s == null) { throw new ArgumentException("Students can only compare with other Students"); } return this.name.CompareTo(s.name); } }