码迷,mamicode.com
首页 > 其他好文 > 详细

4.4.2 空合并操作符让比较不再痛苦

时间:2018-11-22 00:03:25      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:span   string   new   where   ons   cond   alc   oid   ret   

    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadKey();
        }
        static int Compare(Product x, Product y)
        {
            return PartialComparer.Compare(x.Name, y.Name) ?? PartialComparer.Compare(x.Age, y.Age) ?? PartialComparer.Compare(x.Popularity, y.Popularity) ?? 0;
        }
    }
    public class Product
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Popularity { get; set; }
    }
    public static class PartialComparer
    {
        public static int? Compare<T>(T first, T second)
        {
            return Compare(Comparer<T>.Default, first, second);
        }
        public static int? Compare<T>(IComparer<T> compare, T first, T second)
        {
            int ret = compare.Compare(first, second);
            return ret == 0 ? new int?() : ret;
        }
        public static int? ReferenceCompare<T>(T first, T second) where T : class
        {
            return first == second ? 0 : first == null ? -1 : second == null ? 1 : new int?();
        }
    }

 

4.4.2 空合并操作符让比较不再痛苦

标签:span   string   new   where   ons   cond   alc   oid   ret   

原文地址:https://www.cnblogs.com/kikyoqiang/p/9998243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!