Collection -> 由IComparer派生的自定义比较器

博客介绍了继承IComparer接口来自定义比较器,并将其应用于Array.Sort()方法实现自定义排序规则。还给出了示例代码,包含Person类、PersonComparer比较器类,通过随机生成Person数组进行排序,最后可输入元素进行二分查找。

(一). 说明

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();
  }
 }
}


基本语法与结构 命名空间(namespace):用于组织代码,避免命名冲突。 示例:using System; 类与对象:C# 是面向对象语言,基本单元是类(class),通过 new 创建对象。 主方法(Main 方法):程序入口点,格式为 static void Main(string[] args)。 数据类型 值类型:包括整型(int)、浮点型(float, double)、布尔型(bool)、字符型(char)等。 引用类型:如字符串(string)、数组、类实例等。 可空类型:使用 ? 表示可为空的值类型,如 int?。 变量与常量 变量声明:int age = 25; 常量定义:使用 const 关键字,如 const double PI = 3.14159; 运算符 算术运算符:+, -, *, /, % 比较运算符:==, !=, <, >, <=, >= 逻辑运算符:&&, ||, ! 赋值运算符:=, +=, -=, 等 控制流程 条件语句:if, else if, else, switch 循环结构:for, while, do-while, foreach 跳转语句:break, continue, return, goto 数组与集合 数组:固定大小,类型相同元素的集合,如 int[] nums = new int[5]; 集合类:位于 System.Collections.Generic,如 List, Dictionary<TKey, TValue> 方法(函数) 定义格式:访问修饰符 返回类型 方法名(参数列表) 支持方法重载(同名不同参) 面向对象编程(OOP) 封装:通过访问修饰符(public, private, protected)控制成员访问。 继承:使用 : 实现类继承,如 class Dog : Animal 多态:虚方法(virtual)与重写(override)实现运行时多态。 构造函数:初始化对象,可以有多个重载构造函数。 异常处理 使用 try-catch-finally 结构捕获和处理异常。 常见异常类型:NullReferenceException, IndexOutOfRangeException 等。 字符串操作 string 类型不可变,常用方法:Substring(), Replace(), Split(), Trim() 等。 字符串插值:$“Hello, {name}!” 文件与IO操作 使用 System.IO 命名空间进行文件读写,如 File.ReadAllText(), StreamWriter。 委托与事件 委托(Delegate):类型安全的函数指针,用于回调机制。 事件(Event):基于委托的发布-订阅模式,常用于GUI编程。 LINQ(Language Integrated Query) 查询语法:from x in collection where x > 5 select x 方法语法:collection.Where(x => x > 5).Select(x => x) 属性与索引器 属性(Property):提供字段的封装,包含 get 和 set 访问器。 自动属性:public string Name 索引器:允许对象像数组一样通过索引访问。 泛型 提高代码复用性和类型安全性,如 List, Dictionary<TKey, TValue> 自定义泛型类或方法:class MyGeneric 知识点 面向对象编程:封装、继承、多态三大特性,提升代码复用与维护性。 值类型与引用类型区别:值类型存储在栈,引用类型在堆,影响内存管理。 委托与事件机制:实现松耦合设计,支持异步与回调编程模型。 把这些方面的知识深挖形成思维导图
最新发布
11-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值