C#中IComparer的使用

来源:互联网 发布:好的英语软件 编辑:程序博客网 时间:2024/05/01 12:28

(一). 说明

1.继承IComparer接口,可以自定义比较器
2.由于Array.Sort()方法接受IComparer参数,进行自定义排序规则.
   示例中也将IComparer作为Sort方法的参数,将Icomparer应用于Array.Sort()方法

(二).示例代码

using System;
using System.Collections;

namespace 比较器IComparer
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 public class Person
 {
  public int ID;
  public int Age;
  public Person()
  {
   ID=0;
   Age=0;
  }
  public Person(int id,int age)
  {
   ID=id;
   Age=age;
  }
  public void Show()
  {
   Console.WriteLine("年龄={0},代号={1}",Age,ID);
  }
  public static void  ShowPersons(Person []persons)
  {
   foreach(Person person in persons)               
    Console.WriteLine("年龄={0},代号={1}",person.Age,person.ID);
  }
 }
 public class PersonComparer:System.Collections.IComparer
 {
  int System.Collections.IComparer.Compare(object x,object y)
  {
   if(x==null||y==null)
                throw new ArgumentException("参数不能为空");   
   Person temp=new Person();
   if(!x.GetType().Equals(temp.GetType())||!y.GetType().Equals(temp.GetType()))
    throw new ArgumentException("类型不一致");
   temp=null;
   Person personX=(Person)x;
   Person personY=(Person)y;
   if(personX.ID>personY.ID)
    return 1;
   if(personX.ID<personY.ID)
    return -1;
   if(personX.Age>personY.Age)
                return 1;
   if(personX.Age<personY.Age)
    return -1;
   return 0;
  }
 }
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: 在此处添加代码以启动应用程序
   //
   Random rand=new Random();
   Person[] persons=new Person[6];
   Console.WriteLine("随机产生的Person数组为:");
   for(int i=0;i<persons.GetLength(0);i++)
   {
    persons[i]=new Person();
    persons[i].ID=rand.Next()%10;
    persons[i].Age=rand.Next()%50;
    persons[i].Show();
   }
   PersonComparer personComparer=new PersonComparer();
   //System.Collections.IComparer personComparer=new IComparer;
   Array.Sort(persons,personComparer);
   Console.WriteLine("排序后的结果:");
   Person.ShowPersons(persons);
   Person personToBeFind=new Person();
   Console.WriteLine("输入ID");
   personToBeFind.ID=int.Parse(Console.ReadLine());
   Console.WriteLine("输入Age");
   personToBeFind.Age=int .Parse(Console.ReadLine());
   int index=Array.BinarySearch(persons,personToBeFind,personComparer);
   if(index>=0)
    Console.WriteLine("待查找的元素是数组的第{0}个元素",index+1);
   else
    Console.WriteLine("对不起,没有所找的元素");
   Console.ReadLine();
  }
 }
}

原创粉丝点击