C#----用实例来理解IComparable和IComparer

本文通过实例详细介绍了C#中如何使用IComparable接口让自建类支持排序,以及如何利用IComparer接口实现自定义比较规则。通过实现这两个接口,可以方便地对自建类对象数组进行按姓名或分数的升序排序。
摘要由CSDN通过智能技术生成

C#中的基本类型都提供了默认的比较算法,C#可以调用比较算法为基本类型的数组进行排序。

若希望对自建类进行比较或排序,那么可以使用IComparable<T>和IComparer<T>接口。

一、IComparable<T>接口

继承IComparable<T>接口,可以给自建类实现一个通用的比较方法,使自建类的数组可以使用Array. Sort方法进行排序。

实现IComparable<T>接口,要求在类中实现CompareTo方法,该方法参数是一个T类型的对象,返回值必须是-1,0,1中之一。

例子如下:

public class Student : IComparable<Student>
    {
        private string firstName;
        private string lastName;
        private int  englishScore;
        private int  chineseScore;
        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
        {
            get { return firstName; }
            set { firstName = value; }
        }

        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }

        public int EnglishScore
        {
            get { return englishScore; }
            set { englishScore = value; }
        }
        public int ChineseScore
        {
            get { return chineseScore; }
            set { chineseScore = value; }
        }
        public int CompareTo(Student other)
        {
            if (other == null) throw new ArgumentNullException("other");
            int result = string.Compare(this.firstName,other.firstName);

            if (result == 0)
            {
                result = string.Compare(this.lastName, other.lastName);
   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值