C#中的基本类型都提供了默认的比较算法,C#可以调用比较算法为基本类型的数组进行排序。
若希望对自建类进行比较或排序,那么可以使用IComparable<T>和IComparer<T>接口。
一、IComparable<T>接口
继承IComparable<T>接口,可以给自建类实现一个通用的比较方法,使自建类的数组可以使用Array. Sort方法进行排序。
实现IComparable<T>接口,要求在类中实现CompareTo方法,该方法参数是一个T类型的对象,返回值必须是-1,0,1中之一。
例子如下:
public class Student:IComparable<Student>
{
public Student(string firstName,string lastName,int englishScore,int chineseScore)
{
this.FirstName = firstName;
this.LastName = lastName;
this.EnglishScore = englishScore;
this.ChineseScore = chineseScore;
}
public string FirstName;
public string LastName;
public int EnglishScore;
public int ChineseScore;
public int CompareTo(Student other)
{
if (other == null) throw new ArgumentNullException("other");
int result = st

最低0.47元/天 解锁文章
1208

被折叠的 条评论
为什么被折叠?



