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

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);
        }
    }
posted @ 2020-05-08 11:20  13B  阅读(163)  评论(0)    收藏  举报