IComparable与IComparer在c#中的区别是什么

  介绍

IComparable与IComparer在c#中的区别是什么?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

<强> IComparable接口

该接口由其值可以排序或排序的类型实现,并提供强类型的比较方法以对泛型集合对象的成员进行排序,例如数字可以大于第二个数字,一个字符串可以在另一个字符串之前以字母顺序出现。他要求实现类型定义的一个方法,CompareTo (T)该方法指示当前实现在排序顺序中的位置是在同一个类型和第二个对象之前,之后还是与其相同。通常,不会直接从开发人员代码中调用方法。相反他list . sort()和添加等就由方法自动调用。

通常,提供IComparable实现的类型还IEquatable实现接口.IEquatable接口=定义方法,该方法确定实现类型的实例的相等性。

CompareTo (T)方法的实现必须Int32返回具有以下三个值之一的,如下表所示。

值含义小于零此对象在排序顺序中位于CompareTo方法所指定的对象之前。零此当前实例在排序顺序中与CompareTo方法参数指定的对象出现在同一位置。大于零此当前实例位于排序顺序中由CompareTo方法自变量指定的对象之后。

示例:

,, class  Student : IComparable   {才能   ,,,public  string  Name {组,得到,,,}      ,,,public  int  Age {组,得到,,,}   ,,,public  int  CompareTo (object  obj)   ,,,{   ,,,,,if  (! (obj  is 学生))   ,,,,,{   ,,,,,,,throw  new  ArgumentException (“Compared  Object  is  not  of  student");   ,,,,,}   ,,,,,Student  Student =, obj  as 学生;   ,,,,,return  Age.CompareTo (student.Age);   ,,,}   以前,,}

Ps:我们根据通过年龄(int)来进行我们的排序

执行测试

class 程序   {才能   ,,,static  void  Main (string [], args)   ,,,{   ,,,,,ArrayList  studentList =, new  ArrayList  {   ,,,,,,,new 学生{Name=癮"年龄=9,},   ,,,,,,,,new 学生{Name=癮3",年龄=7,},   ,,,,,,,,new 学生{Name=癮1"年龄=6,},   ,,,,,,,,new 学生{Name=癮2",年龄=10,},   ,,,,,};   ,,,,,studentList.Sort ();   ,,,,,StudentComparable (studentList);      ,,,,,Console.ReadLine ();   ,,,}      ,,,private  static  void  StudentComparable (ArrayList  studentList)   ,,,{   ,,,,,foreach  (Student  item  studentList拷贝)   ,,,,,{   ,,,,,,,Console.WriteLine(“名字:{0},年龄:{1},,,item.Name,, item.Age);   ,,,,,}   ,,,}   以前,,}

输出如下

 IComparable与IComparer在c#中的区别是什么

<强> IComparer接口

IComparable接口的CompareTo方法一次只能对一个字段进行排序,因此无法对不同的属性进行排序.IComparer接口提供了比较方法,该方法比较两个对象并返回一个值,该值指示一个对象小于,等于或大于另一个对象。实现IComparer接口的类必须提供比较两个对象的比较方法,例如,您可以创建一个StudentComparer类,该类实现IComparer,并具有一个比较方法,该方法按名字比较学生对象,然后,您可以将StudentComparer对象传递给数组。这种方法,它可以使用该对象对学生对象的数组进行排序。

示例

,, class  StudentComparer : IComparer   {才能      ,,,public  int 比较(object  x,, object  y)   ,,,{   ,,,,,Student  x1 =, x  as 学生;   ,,,,,Student  y1 =, y  as 学生;   ,,,,,return  x1.Name.CompareTo (y1.Name);   ,,,}   以前,,}

Ps:我们根据名称(字符串)进行排序

执行测试

, class 程序   {才能   ,,,static  void  Main (string [], args)   ,,,{   ,,,,,ArrayList  studentList =, new  ArrayList  {   ,,,,,,,new 学生{Name=癮"年龄=9,},   ,,,,,,,,new 学生{Name=癮3",年龄=7,},   ,,,,,,,,new 学生{Name=癮1"年龄=6,},   ,,,,,,,,new 学生{Name=癮2",年龄=10,},   ,,,,,};   ,,,,,studentList.Sort (new  StudentComparer ());   ,,,,,StudentComparable (studentList);      ,,,,,Console.ReadLine ();   ,,,}      ,,,private  static  void  StudentComparable (ArrayList  studentList)   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

IComparable与IComparer在c#中的区别是什么