gpt4 book ai didi

c# List 排序 : by Chinese strokes

转载 作者:太空狗 更新时间:2023-10-29 20:01:46 26 4
gpt4 key购买 nike

我有一个网页,其中有一个排序,我必须按汉字排序列表。

我创建了一个包含如下代码的应用程序:

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 接口(interface)。这需要实现一个方法 CompareTo,它可以简单地返回在您尝试排序的字符串之间调用 CompareTo 的结果。

例如,如果构造函数初始化一个 name 字段,您可能有这样的东西:

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

关于c# List<T> 排序 : by Chinese strokes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8206644/

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