您的位置:首页 > 编程语言 > C#

C#中IComparable<T>和IComparer<T>接口的使用

2016-10-10 21:39 477 查看
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 = string.Compare(this.FirstName, other.FirstName);//result会根据两个string对象返回-1,0或者1
if (result==0)
{
result = string.Compare(this.LastName, other.LastName);//若两个实例的FirstName相同,则按照LastName排序
}
return result;
}
}在Main方法中运行以下代码:
Student[] students = new Student[]
{
new Student("Mary", "Yang", 60, 77),
new Student("Jane", "Pope",80,75),
new Student("Jack", "Baker", 55, 70),
new Student("Jane", "Chan", 61, 90),
};
Array.Sort(students);
foreach (var student in students)
{
Console.WriteLine(student.FirstName + " " + student.LastName + " English:" + student.EnglishScore + " Chinese:" + student.ChineseScore);
}输出结果是:
Jack Baker English:55 Chinese:70
Jane Chan English:61 Chinese:90
Jane Pope English:80 Chinese:75
Mary Yang English:60 Chinese:77可以看到,4个学生的信息被按照名字顺序排序。
二、IComparer<T>接口

IComparer<T>可以提供了CompareTo方法,并且可以接受参数,以用户需要的比较类型排序。

例子中的StudentComparer类提供了两种不同的为Student数组排序的方法:

public enum StudentCompareType
{
ChineseScore,
EnglishScore
}

public class StudentComparer : IComparer<Student>
{
private StudentCompareType compareType;

public StudentComparer(StudentCompareType compareType)
{
this.compareType = compareType;
}

public int Compare(Student x, Student y)
{
switch (compareType)
{
case StudentCompareType.ChineseScore:
return x.ChineseScore.CompareTo(y.ChineseScore);
break;
case StudentCompareType.EnglishScore:
return x.EnglishScore.CompareTo(y.EnglishScore);
break;
default:
throw new ArgumentException("unexpected compare type");
break;
}
}
}

使用之前创建的student数组,在Main方法中运行以下代码:
Array.Sort(students, new StudentComparer(StudentCompareType.Chi<span id="transmark" style="display: none; width: 0px; height: 0px;"></span>neseScore));
foreach (var student in students)
{
Console.WriteLine(student.FirstName + " " + student.LastName + " English:" + student.EnglishScore + " Chinese:" + student.ChineseScore);
}

可以得到运行结果:
Jack Baker English:55 Chinese:70
Jane Pope English:80 Chinese:75
Mary Yang English:60 Chinese:77
Jane Chan English:61 Chinese:90

可以看到,学生被按照语文成绩排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C#
相关文章推荐