首页 > 其他 > 详细

通过IComparable<T>、IComparer<T>定义顺序

时间:2020-05-08 13:37:20      阅读:53      评论:0      收藏:0      [点我收藏+]

IComparable、IComparer接口 相关接口介绍


    public struct Customer: IComparable<Customer>, IComparable
    {
        //根据名称排序(默认)
        private readonly string name;
        //根据收益排序
        private double revenue;

        public Customer(string name,double revenue)
        {
            this.name = name;
            this.revenue = revenue;
        }

        public int CompareTo(Customer other) => name.CompareTo(other.name);

        public int CompareTo(object obj)
        {
            if (!(obj is Customer))
                throw new ArgumentException(
                    "Argument is not a Customer", "obj");
            Customer otherCustomer = (Customer)obj;
            return this.CompareTo(otherCustomer);
        }

        public static bool operator <(Customer left, Customer right) => left.CompareTo(right) < 0;
        public static bool operator <=(Customer left, Customer right) => left.CompareTo(right) <= 0;
        public static bool operator >=(Customer left, Customer right) => left.CompareTo(right) >= 0;
        public static bool operator >(Customer left, Customer right) => left.CompareTo(right) > 0;

        // 实现懒加载(第一次调用时才构造)
        private static Lazy<RevenueComparer> revComp = new Lazy<RevenueComparer>(() => new RevenueComparer());
        // 得到RevenueComparer实例 Instance.Sort(Instance.RevenueCompare)
        public static IComparer<Customer> RevenueCompare => revComp.Value;
        public static Comparison<Customer> CompareByRevenue => (left, right) => left.revenue.CompareTo(right.revenue);

        // 实现ICompare可以在调用Sort方法时根据Revenue排序
        private class RevenueComparer : IComparer<Customer>
        {

            public int Compare(Customer left, Customer right) => left.revenue.CompareTo(right.revenue);
        }
    }

通过IComparable<T>、IComparer<T>定义顺序

原文:https://www.cnblogs.com/jarryHu/p/12849416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!