C#中IComparable<T>和IComparer<T>接口的使用

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

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

一、IComparable<T>接口

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

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

例子如下:

public class Student:IComparable<Student>
    {
        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;
        public string LastName;
        public int EnglishScore;
        public int ChineseScore;
        public int CompareTo(Student other)
        {
            if (other == null) throw new ArgumentNullException("other");
            int result = st
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值