C# 中的IComparable和IComparer的使用及区别
前言
在开发过程中经常会遇到比较排序的问题,比如说对集合数组的排序等情况,基本类型都提供了默认的比较算法,如string提供了按字母进行排序,而int整数则是根据整数大小进行排序.但是在引用类型中(具有多个字段),那么这个排序当然也是取决于我们特定的值。
IComparable接口
该接口由其值可以排序或排序的类型实现,并提供强类型的比较方法以对泛型集合对象的成员进行排序,例如数字可以大于第二个数字,一个字符串可以在另一个字符串之前以字母顺序出现。他要求实现类型定义的一个方法,CompareTo(T)该方法指示当前实现在排序顺序中的位置是在同一个类型和第二个对象之前、之后还是与其相同。通常,不会直接从开发人员代码中调用方法。相反他由List
通常,提供Icomparable
CompareTo(T)方法的实现必须Int32返回具有以下三个值之一的,如下表所示。
值 | 含义 |
---|---|
小于零 | 此对象在排序顺序中位于CompareTo方法所指定的对象之前。 |
零 | 此当前实例在排序顺序中与CompareTo方法参数指定的对象出现在同一位置。 |
大于零 | 此当前实例位于排序顺序中由CompareTo方法自变量指定的对象之后。 |
示例:
classStudent:IComparable { publicstringName{get;set;} publicintAge{get;set;} publicintCompareTo(objectobj) { if(!(objisStudent)) { thrownewArgumentException("ComparedObjectisnotofstudent"); } Studentstudent=objasStudent; returnAge.CompareTo(student.Age); } }
Ps:我们根据通过Age(int)来进行我们的排序
执行测试
classProgram { staticvoidMain(string[]args) { ArrayListstudentList=newArrayList{ newStudent{Name="a",Age=9}, newStudent{Name="a3",Age=7}, newStudent{Name="a1",Age=6}, newStudent{Name="a2",Age=10}, }; studentList.Sort(); StudentComparable(studentList); Console.ReadLine(); } privatestaticvoidStudentComparable(ArrayListstudentList) { foreach(StudentiteminstudentList) { Console.WriteLine("Name:{0},Age:{1}",item.Name,item.Age); } } }
输出如下
IComparer接口
IComparable接口的CompareTo方法一次只能对一个字段进行排序,因此无法对不同的属性进行排序。IComparer接口提供了Compare方法,该方法比较两个对象并返回一个值,该值指示一个对象小于,等于或大于另一个对象。实现IComparer接口的类必须提供比较两个对象的Compare方法。例如,您可以创建一个StudentComparer类,该类实现IComparer,并具有一个Compare方法,该方法按Name比较Student对象。然后,您可以将StudentComparer对象传递给Array.Sort方法,它可以使用该对象对Student对象的数组进行排序。
示例
classStudentComparer:IComparer { publicintCompare(objectx,objecty) { Studentx1=xasStudent; Studenty1=yasStudent; returnx1.Name.CompareTo(y1.Name); } }
Ps:我们根据Name(string)进行排序
执行测试
classProgram { staticvoidMain(string[]args) { ArrayListstudentList=newArrayList{ newStudent{Name="a",Age=9}, newStudent{Name="a3",Age=7}, newStudent{Name="a1",Age=6}, newStudent{Name="a2",Age=10}, }; studentList.Sort(newStudentComparer()); StudentComparable(studentList); Console.ReadLine(); } privatestaticvoidStudentComparable(ArrayListstudentList) { foreach(StudentiteminstudentList) { Console.WriteLine("Name:{0},Age:{1}",item.Name,item.Age); } } }
输出结果如下
IComparable
上述示例中我们将对象进行了多次的装箱和拆箱,那么此时我们可以将方法改为泛型的,泛型的出现也让我们避免了装箱和拆箱的资源浪费.
最终我们实现的代码片段如下:
IComparable
classStudent:IComparable{ publicstringName{get;set;} publicintAge{get;set;} publicintCompareTo([AllowNull]Studentother) { returnAge.CompareTo(other.Age); } }
IComparer
classStudentComparer:IComparer{ publicintCompare([AllowNull]Studentx,[AllowNull]Studenty) { returnx.Name.CompareTo(y.Name); } }
总结
参考:https://docs.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netframework-4.8
示例:https://github.com/hueifeng/BlogSample/tree/master/src/CompareDemo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。